所以我有一个演示应用程序,其中我通过root的计算属性生成一个随机数,然后使用prop将计算值传递给子组件。
每当我在点击时生成随机值时,我都无法找出正确的方法来更新子组件中的值。
另外,jquery dom选择很奇怪,它有时给我未定义的信息,有时它起作用并突出显示单元格。
这是我的codepen
Vue.component('grid',{
template:'#grid',
props:['randval'],
data:function(){
return{
title:"items",
items:["A","B","C","D","E","F","G","H","I"]
}
},
computed:{
getValues:function(){
$('.cells').removeClass('highlight');
$('#cell_'+this.randval).addClass('highlight');
console.log($('#cell_').text(), this.$refs.cell_1); // for example this return undefined sometime and works other times
return this.randval;
}
}
});
let app = new Vue({
el:"#app",
data:{
val:0
},
methods:{
randFun:function(){
this.val = parseInt(Math.random()*10);
}
},
computed:{
watchVal:function(){
return (this.val<9)?this.val:0;
}
}
});
答案 0 :(得分:1)
您可以使用v-bind:class
您还可以watch
一个道具值。
computed: {
getValues:function(){
// ...
}
},
watch: {
randval(newVal, oldVal) {
console.log('newVal: ', newVal);
console.log('oldVal: ', oldVal);
}
}
<li v-for="item, i in items" class="cells"
:class="{ highlight: (i === randval) }">
答案 1 :(得分:0)
像这样更新组件,看来这是更新道具并观看道具的唯一方法-
Vue.component('grid',{
template:'#grid',
props:['randval'],
data:function(){
return{
title:"items",
items:["A","B","C","D","E","F","G","H","I"],
final:0
}
},
watch: {
randval:function(){
this.final = this.randval;
console.log('watching randvals-->',this.randval);
}
},
});
答案 2 :(得分:0)
您可以使用触发道具。更新触发道具后,我们可以从随机分量中生成新的随机值。
Vue.component('grid',{
template:'#grid',
props:['randval'],
data:function(){
return{
title:"items",
items:["A","B","C","D","E","F","G","H","I"]
}
}
});
Vue.component('random', {
props: [
'trigger',
'min',
'max'
],
computed: {
random() {
this.trigger;
return Math.floor(Math.random() * (this.max - this.min + 1) + this.min);
} },
render() {
return this.$scopedSlots.default({
random: this.random
});
}
});
let app = new Vue({
el:"#app",
data:{
trigger:0
},
methods:{
randFun:function(){
this.trigger = this.trigger+1;
}
}
});
ul{
list-style:none;
margin:0;
padding:0;
font-family:'Roboto';
display:grid;
grid-template-columns:repeat(3,1fr);
}
li{
padding:10px;
border:1px solid #aaa;
display:grid;
grid-template-columns:1fr 1fr;
align-items:center;
justify-items:center;
}
li:hover{
background:#eee;
}
.highlight{
background:#7ed6df;
color:#130f40;
}
<script src="https://unpkg.com/vue"></script>
<div id="app">
<random v-slot="{random}" :trigger="trigger" max="9" min="1" >
<grid v-bind:randval="random"></grid>
</random>
<button v-on:click="randFun">CLICK</button>
</div>
<script type="text/x-template" id="grid">
<ul>
<li v-for="item, i in items" v-bind:id='"cell_"+i' v-bind:ref='"cell_"+i' class="cells" :class="{ highlight: (i === randval) }">
<span>{{item}}</span><span>{{i}}</span>
</li>
</ul>
</script>