鍍金池/ 問答/HTML/ vue2.0 父組件像子組件傳值

vue2.0 父組件像子組件傳值

父組件

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  <conter num="10"></conter>
  </div>
</template>
<script>
import conter from "./conter";
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App,test it111"
    };
  },
  components: {
    conter
  }
};
</script>

子組件

<template>
  <div>
      <button @click="add">+</button>
      <button @click="del">-</button>
      <p>{{num}}</p>
  </div>
</template>

<script>
export default {
props:["num"],
  data () {
    return {
       
    };
  },
  methods: {
      add(){
          this.num++
      },
      del(){
          this.num--
      }
  }
}

</script>

點擊子組件的按鈕時報錯:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "num"
回答
編輯回答
夏夕

簡要的意思是你不應(yīng)該在父組件給默認(rèn)值,應(yīng)該在子組件賦默認(rèn)值。

props:{
  num:{
   type:number,
   default:10
  }
}

而且你父組件,計算值時 要 :num="10"
出現(xiàn)這種問題,你應(yīng)該沒仔細(xì)看官方文檔吧,親。

2018年8月30日 07:45