怎樣解決 [Vue warn]: The computed property "count" is already defined in data. 報錯問題?

周行知發表於2018-01-06

最近在寫vue專案時候發現一個專案中報如下錯誤

vue.esm.js?5425:578 [Vue warn]: Property or method "counit" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.


found in


---> <App> at src\Vuex.vue
       <Root>

程式碼如下:

store.js:

import Vue from 'vue'
import Vuex from 'vuex'//記得用cnpm install vuex --save
Vue.use(Vuex)
const state={//狀態物件
count:4
}
const mutations={//觸發狀態
jia(state){
state.count++;
},
jian(state){
state.count--;
}


}
export default new Vuex.Store({



state,
mutations
})

main.js註冊:

import Vue from 'vue'
import App from './App'
import router from './router'
import store from'./store'
import vuex from'./Vuex'
Vue.config.productionTip = false

new Vue({

  el: '#app',
   router,
 
  template: '<App/>',
   components: { App },
  store,
  render:xx=>xx(vuex)

})

vuex.vue程式碼如下:

<template>
<div id="app">
<h1>Hello,World</h1>
<p>{{$store.state.count}}-{{count}} </p>
<button @click="$store.commit('jia')">+</button>
<button @click="$store.commit('jian')">-</button>
</div>
</template>


<script>
export default{
name:'app',


data(){
return {


count:0
}
},
computed:{
count(){
return   this.$store.state.count
}
}
}
</script>


<style>
</style>

我當時搞了半天還是沒解決,後來我用有道翻譯了此句話The computed property "count" is already defined in data的意思:計算的屬性“count”已經在資料中定義。那麼照此推理,main.js和store.js沒有問題,後來我把計算屬性中computed中count改為counit並且把-{{count}}改為-{{counit}}問題解決。這說明計算屬性的名字不能與data中屬性同名。

相關文章