2017-09-30 42 views
1

我從VueJS 2開始,創建了一個簡單的插件,它將參數添加到Vue實例中。VueJS觀察插入參數

我有問題,因爲當我更新這個值時,我的計算屬性仍然是相同的。

我的例子插件的代碼:

export default function (Vue) { 
    Vue.MyProperty = "test" 

    Object.defineProperties(Vue.prototype, { 
     "$myProperty": { 
      "get": function() { 
       return Vue.MyProperty 
      }, 

      "set": function (value) { 
       Vue.MyProperty = value 

       return this 
      } 
     } 
    }) 
} 

而我的組件的代碼

export default { 
    "computed": { 
     "test": function() { 
      return this.$myProperty 
     } 
    } 
} 

當我在其他組件更改this.$myProperty我的分量返回VAID值(例如,當我從"test"變成"newvalue"我可以看到"newvalue")但計算出的屬性test仍然是舊值(在我的示例中爲"test")。

我試圖使用this.$set(this, "$myProperty", value)但這仍然無法正常工作。

如何使用或聲明此屬性以在計算或觀察屬性中使用它?

回答

1

數據值未在計算中自動更新的原因是因爲您添加到Vue的屬性MyProperty不是觀察到的屬性。基本上,Vue的反應性是有效的,因爲所有加入到數據的值都轉換成,觀察到的屬性;在引擎蓋下,它們被轉換成帶有一些附加代碼的getter/setter對,以便當其中一個屬性改變時,Vue知道將改變傳播到所有依賴於它的值的事物。

然而,問題中的代碼只是爲Vue對象添加了一個普通屬性。你可以改變它,但它不是被動的。

這就是說,使其成爲被動方式相對容易。我在我的回答here的評論中介紹瞭如何做到這一點。基本上,不是將您的屬性添加到Vue,而是創建一個新的Vue對象(開銷非常低),並使您想要反應的屬性成爲該Vue的屬性。這是一個工作示例。

console.clear() 
 

 
function MyPlugin(Vue) { 
 
    let store = new Vue({data:{MyProperty: "some value"}}) 
 

 
    Object.defineProperties(Vue.prototype, { 
 
     "$myProperty": { 
 
      "get": function() { 
 
       return store.MyProperty 
 
      }, 
 

 
      "set": function (value) { 
 
       store.MyProperty = value 
 

 
       return this 
 
      } 
 
     } 
 
    }) 
 
} 
 

 
Vue.use(MyPlugin) 
 

 
const MyComponent = { 
 
    template:`<div>{{test}}</div>`, 
 
    "computed": { 
 
     "test": function() { 
 
      return this.$myProperty 
 
     } 
 
    } 
 
} 
 

 
new Vue({ 
 
    el: "#app", 
 
    components:{ 
 
    MyComponent 
 
    } 
 
})
<script src="https://unpkg.com/[email protected]"></script> 
 
<div id="app"> 
 
    <my-component></my-component> 
 
    <button @click="$myProperty = 'new value'">Change</button> 
 
</div>

+0

我能說什麼 - 這是非常聰明的使用第二Vue的實例:)我找到不同的解決辦法,但你也是聰明 – ventaquil