如何将数据对象的值放入另一个数据对象 vueJS [英] How to put a value of data object in another data object vueJS
问题描述
这是我的代码:
data () {
return {
msg: '',
rgbValue: '',
newColor: {
color: this.msg
}
}
}
此代码不起作用.我想将 msg
的值放在我的对象 newColor
中.有没有人有办法解决吗?
This code doesn't work. I would like to put the value of msg
in my object newColor
. Does anyone have a solution?
下面是代码的补充:
data () {
let msg = '';
return {
msg: msg,
rgbValue: '',
newColor: {
color: msg
}
}
},
components: {
HeaderComponent: require('./HeaderComponent.vue')
},
methods: {
msgFunc: function () {
colorsRef.push(this.newColor);
const app = document.querySelector('#app');
const rgbValueContainer = document.querySelector('.rgb-value');
if (this.msg[0] !== '#') {
this.msg = '#'
}
app.style.backgroundColor = this.msg
function convert(hex) {
hex = hex.replace('#', '');
const r = parseInt(hex.length == 3 ? hex.slice(0, 1).repeat(2) : hex.slice(0, 2), 16);
const g = parseInt(hex.length == 3 ? hex.slice(1, 2).repeat(2) : hex.slice(2, 4), 16);
const b = parseInt(hex.length == 3 ? hex.slice(2, 3).repeat(2) : hex.slice(4, 6), 16);
return 'rgb(' + r + ', ' + g + ', ' + b + ')';
}
this.rgbValue = convert(this.msg)
rgbValueContainer.style.opacity = '1'
this.msg = '#'
}
<section class="input-container">
<label for="inputLabel">Type your HEX color | Click & Press enter</label>
<input type="text" id="inputLabel" v-model="msg" @change="msgFunc" @click="sharpStr">
</section>
你可以在 msgFunc 之后看到推送到我的数据库,问题就在这里,他正确推送了对象,但他没有更新颜色的值
You can see just after msgFunc, the push on my DB, and the problem is here, he push correctly object, but he don't update the value of color
推荐答案
您将无法访问像 this.msg
这样的数据属性,直到 data
方法具有回来.
You won't be able to access data properties like this.msg
until the data
method has returned.
只需在 return
语句之外设置该值:
Just set that value outside of the return
statement:
data () {
let msg = '';
return {
msg: msg,
rgbValue: '',
newColor: {
color: msg
}
}
}
<小时>
如果您需要 newColor
属性始终反映 this.msg
的值,您可以改为将其设为计算属性:
If you need the newColor
property to always reflect the value of this.msg
, you could make it a computed property instead:
data () {
return {
msg: '',
rgbValue: '',
}
},
computed: {
newColor() {
return { color: this.msg }
}
}
这篇关于如何将数据对象的值放入另一个数据对象 vueJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!