子组件未从父组件更新值 [英] Child component not update value from Parent

查看:28
本文介绍了子组件未从父组件更新值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的 vue js.我不知道为什么当我更改父组件中的值时子组件中的值不更新.谁能为我解释一下?我知道我可以使用 Times Updated: {{ times}} 来显示.但我想把它赋值给 count 来做别的事情

父母HTML

<button @click="clicktime">点击</button><times-updated :times.sync="myData"></times-updated>

.js 文件

var vm = new Vue({el: '#test',数据(){返回 {我的数据:100}},方法: {点击时间(){vm.myData = Math.random();}}})

孩子

Vue.component('times-updated', {道具:[时代"],数据() {返回 {计数:this.times}},模板:'<span>更新次数:{{ count }}</span>',});

链接代码笔:在此处输入链接描述

解决方案

你需要computed 数据而不是数据元素,它会保持监视和更新

Vue.component('times-updated', {道具:[时代"],计算:{计数:函数(){返回 this.times;}},模板:'<span>更新次数:{{count}}</span>',});var vm = new Vue({el: '#test',数据(){返回 {我的数据:100}},方法: {点击时间(){vm.myData = Math.random();}}})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script><div id="测试"><button @click="clicktime">点击</button><times-updated :times.sync="myData"></times-updated>

I am new vue js. I don't know why value in child component not update when I change value in parent component. Can anyone explain for me? I know that I can use Times Updated: {{ times}} to display. But I want to assign it into count to do something else

Parent HTML

<div id="test">
  <button @click="clicktime">Click</button>
  <times-updated :times.sync="myData"></times-updated>
</div>

.js file

var vm = new Vue({
  el: '#test',
  data(){
    return {
      myData: 100
    }
  },

  methods: {
    clicktime() {
      vm.myData = Math.random();
    }
  }
})

Child

Vue.component('times-updated', {
  props:["times"],
  data() {
    return {
      count: this.times
  }
},
  template: '<span>Times Updated: {{ count }}</span>',
});

link codepen: enter link description here

解决方案

You need computed data instead data element, which keep watch and updates

Vue.component('times-updated', {
  props:["times"],
  computed: {
    count: function(){
       return this.times;
    }
  },
  template: '<span>Times Updated: {{count}}</span>',
});

var vm = new Vue({
  el: '#test',
  data(){
    return {
      myData: 100
    }
  },

  methods: {
    clicktime() {
      vm.myData = Math.random();
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
<div id="test">
  <button @click="clicktime">Click</button>
  <times-updated :times.sync="myData"></times-updated>
</div>

这篇关于子组件未从父组件更新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆