需要与计算 属性 相同的功能,但我需要能够在初始更改后更新数据
Need the same functionality as a computed property, but I need to be able to update the data after initial change
我遇到一种情况,当它检测到状态发生变化时我需要更新数据。用户需要能够在文本区域内进一步更改此信息。使用计算属性完全按照我想要的方式提取数据,但是在此之后用户所做的任何更改都将被覆盖,因为计算 属性 不断将此数据更改回其初始值。在状态更改时最初提取数据但随后允许在该点之后进行编辑的最佳方法是什么?
谢谢!
编辑:更新为我为@Libby 尝试过的内容。
<textarea v-model="exampleData"></textarea>
computed: {
...mapGetters({
item: 'item'
})
methods: {
exampleFunction() {
this.exampleData = this.item;
}
mounted() {
this.exampleFunction();
}
如果你在data
中设置你的属性,你可以在mounted
中初始化它,它只在页面加载时运行一次:
data:
text: null
mounted: ->
text = "This text is initialized"
然后在你的 textarea
上设置 v-model
<textarea v-model="text"></textarea>
因此 textarea
的值将以 "This text is initialized" 开始,但用户可以更改它,并且这些更改将保存在 text
在 item
的观察者中更新 exampleData
:
watch: {
item(value) {
this.exampleData = value;
}
}
这样您可以将 exampleData
绑定到文本字段,但对 item
的更改仍会影响它。
如果您希望 exampleData
初始设置为 item
的值,请在组件的 mounted
挂钩中执行此操作:
mounted() {
this.exampleData = this.item;
}
如果你对 computed properties
使用 getter/setter 语法,Vue 已经有一个内置的解决方案来处理这个问题
computed: {
fullName: {
// getter
get: function () {
return this.firstName + ' ' + this.lastName
},
// setter
set: function (newValue) {
var names = newValue.split(' ')
this.firstName = names[0]
this.lastName = names[names.length - 1]
}
}
}
因此,当您的状态发生变化时,您可以通过为计算机分配一个值来更新计算机属性:
// state has changed in text area handler
this.fullName = 'new value'
我遇到一种情况,当它检测到状态发生变化时我需要更新数据。用户需要能够在文本区域内进一步更改此信息。使用计算属性完全按照我想要的方式提取数据,但是在此之后用户所做的任何更改都将被覆盖,因为计算 属性 不断将此数据更改回其初始值。在状态更改时最初提取数据但随后允许在该点之后进行编辑的最佳方法是什么?
谢谢!
编辑:更新为我为@Libby 尝试过的内容。
<textarea v-model="exampleData"></textarea>
computed: {
...mapGetters({
item: 'item'
})
methods: {
exampleFunction() {
this.exampleData = this.item;
}
mounted() {
this.exampleFunction();
}
如果你在data
中设置你的属性,你可以在mounted
中初始化它,它只在页面加载时运行一次:
data:
text: null
mounted: ->
text = "This text is initialized"
然后在你的 textarea
上设置v-model
<textarea v-model="text"></textarea>
因此 textarea
的值将以 "This text is initialized" 开始,但用户可以更改它,并且这些更改将保存在 text
在 item
的观察者中更新 exampleData
:
watch: {
item(value) {
this.exampleData = value;
}
}
这样您可以将 exampleData
绑定到文本字段,但对 item
的更改仍会影响它。
如果您希望 exampleData
初始设置为 item
的值,请在组件的 mounted
挂钩中执行此操作:
mounted() {
this.exampleData = this.item;
}
如果你对 computed properties
使用 getter/setter 语法,Vue 已经有一个内置的解决方案来处理这个问题computed: { fullName: { // getter get: function () { return this.firstName + ' ' + this.lastName }, // setter set: function (newValue) { var names = newValue.split(' ') this.firstName = names[0] this.lastName = names[names.length - 1] } } }
因此,当您的状态发生变化时,您可以通过为计算机分配一个值来更新计算机属性:
// state has changed in text area handler
this.fullName = 'new value'