我正在使用 Vue 3 。我无法从按钮获取数据集值:
这是按钮:
<script src="https://unpkg.com/[email protected]/dist/vue.global.js"></script>
<button id="profile"
v-on:click="start" :data-id="19876"
class="profile"
data-gender="{{$gender}}">
</button>
这是我的 vue 对象:
<script>
Vue.createApp({
data() {
return {
state: null,
};
},
mounted() {
console.log(this);
},
methods: {
startChat(event){
// const { id } = event.target.dataset;
var id = event.target.getAttribute('data-id');
console.log(id);
},
}
}).mount('#profile');
</script>
这将返回值 null。
我也尝试过这个:
const { id } = event.target.dataset;
其返回值未定义。
您将 Vue 直接安装在
#profile
按钮上,但当安装在包含按钮的包装元素(例如<div>
)上时,Vue 效果最佳。由于按钮本身是 Vue 实例的根,因此 Vue 接管并删除 data-* 属性,这就是您无法获得预期值的原因。要修复此问题,请将按钮包裹在里面,然后将 Vue 安装到该 div 上。
在官方文档中了解有关安装 Vue 的更多信息
如果在我的 html 中有类似这样的内容(在我的情况下是 blade.php):
我可以在我的 vue 组件中像这样访问这些数据:
但一切正常。您的代码中有错误。例如,您调用了该方法,但单击事件由...
startChat
处理。 应该是这样的:start
Vue SFC 游乐场