Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

vue.js - How to put a value of data object in another data object vueJS

Here is my code:

data () {
  return {
    msg: '',
    rgbValue: '',
    newColor: {
      color: this.msg
    }
  }
}

This code doesn't work. I would like to put the value of msg in my object newColor. Does anyone have a solution?

Here is a complement of code :

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You won't be able to access data properties like this.msg until the data method has returned.

Just set that value outside of the return statement:

data () {
  let msg = '';

  return {
    msg: msg,
    rgbValue: '',
    newColor: {
      color: 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 }
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...