gpt4 book ai didi

javascript - 未在 Vue 中调用的计算属性集

转载 作者:行者123 更新时间:2023-12-01 17:15:49 24 4
gpt4 key购买 nike

根据文档,我应该能够在 Vue 中使用计算属性作为 v-model,只要我定义了 get/set 方法,但在我的例子中它不起作用:

export default{

template: `
<form class="add-upload" @submit.prevent="return false">
<label><input type="checkbox" v-model="options.test" /> test </label>
</form>
`,

computed: {

options: {

get(){
console.log('get');
return {test: false};
},

set(value){
console.log('set');
},

},

}

}

显然,当我选中/取消选中输入时,set 不会被调用。但是 get 在显示组件时被调用...

最佳答案

编辑:在阅读了您依赖本地存储的评论后,我只能建议您采用 Vuex 方法并使用持久性库来处理本地存储。 ( https://www.npmjs.com/package/vuex-persist )这样,您的本地存储将始终链接到您的应用程序,您不必每次都搞乱 getItem/setItem。

看看您的方法,我假设您有理由在数据属性上使用计算属性。

问题的发生是因为您的计算属性返回了一个在 get 处理程序中定义的对象。无论您尝试什么,您都无法在 set 处理程序中操作该对象。

getset 必须链接到一个公共(public)引用。正如许多人所建议的那样,数据属性或应用程序中的真实来源(Vuex 实例就是一个很好的例子)。

这样,您的 v-model 将与计算属性的 set 处理程序一起完美地工作。

这是一个演示解释的工作 fiddle :

使用 Vuex

const store = new Vuex.Store({
state: {
// your options object is predefined in the store so Vue knows about its structure already
options: {
isChecked: false
}
},
mutations: {
// the mutation handler assigning the new value
setIsCheck(state, payload) {
state.options.isChecked = payload;
}
}
});

new Vue({
store: store,
el: "#app",
computed: {
options: {
get() {
// Here we return the options object as depicted in your snippet
return this.$store.state.options;
},
set(checked) {
// Here we use the checked property returned by the input and we commit a Vuex mutation which will mutate the state
this.$store.commit("setIsCheck", checked);
}
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}

#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}

h2 {
font-weight: bold;
margin-bottom: 15px;
}
<div id="app">
<h2>isChecked: {{ options.isChecked }}</h2>
<input type="checkbox" v-model="options.isChecked" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vuex@2.0.0"></script>

有一个数据属性

new Vue({
el: "#app",
data: {
options: {
isChecked: false
}
},
computed: {
computedOptions: {
get() {
return this.options;
},
set(checked) {
this.options.isChecked = checked;
}
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}

#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}

h2 {
font-weight: bold;
margin-bottom: 15px;
}
<div id="app">
<h2>isChecked: {{ computedOptions.isChecked }}</h2>
<input type="checkbox" v-model="computedOptions.isChecked" />
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

恕我直言,您的方法有点特别,但您必须有理由这样做。

关于javascript - 未在 Vue 中调用的计算属性集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62943179/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com