如何在VUE读取'data-val'属性的值中同步变量“ counter”?在此示例中,我使用setTimeout更改data- *属性值。我的解决方案是通过@mousemove事件调用refresh()方法。
new Vue({
el: '#app',
data: {
counter: 1
},
template: '<div id="wrapper" @mousemove="refresh"><div id="el1" :data-val="counter">Value: {{ counter }}</div></div>',
watch: {
counter: function(val, oldVal){
this.counter = val;
}
},
methods: { refresh() {
this.counter = document.getElementById('el1').getAttribute("data-val");
}
}
});
var i=1;
timer = setInterval(changeDOM, 1500);
function changeDOM() {
i++;
el=document.getElementById('el1');
el.setAttribute("data-val", i);
console.log(el.getAttribute("data-val"));
}
#wrapper{
width: 100%;
height: 100%;
background-color: aqua;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>
答案 0 :(得分:0)
有很多方法可以实现您的目标,但是如果您想要使用vue实例,则需要在如下所示的变量中分配vue实例
var app = new Vue({
然后将counter
更改为app.counter
var app = new Vue({
el: '#app',
data: {
counter: 1
},
template: `<div id="el1" :data-val="counter">
<div>Value: {{ getCounter }}</div>
<div><input type="text" v-model="counter"></div>
</div>`,
computed: {
getCounter: function(val, oldVal){
return this.callMethod1(this.counter);
}
},
methods:{
callMethod1: function(){
console.log("callMethod1 called with counter value : "+this.counter);
return this.counter;
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>