如何在Vue.js中声明反应性属性

jos*_*dev 4 javascript vue.js vue-router vue-component

这是Vue-routes应用程序的一部分,在其中一个路由中,我具有两个属性bga和bgb,这些属性将用于更改div的颜色。我不知道如何正确声明它们,该怎么做?

我在Chrome控制台中收到以下消息:

  • vue.js:597 [Vue警告]:“数据”选项应该是一个在组件定义中返回每个实例值的函数。警告@ vue.js:597

  • vue.js:597 [Vue警告]:属性或方法“ bga”,“ bgb”未在实例上定义,但在渲染期间被引用。通过初始化属性,确保该属性在data选项中或对于基于类的组件都是反应性的。请参阅:https : //vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties

ColorPage.js

const ColorPage = {
    props:
        ['bga', 'bgb'],
    data: {
        bga: {
            backgroundColor: ''
        },
        bgb: {
            backgroundColor: ''
        }
    },
    template: `
<div id="middle">
    <label id="colorLabel"><h2>'Change Colors By Typing Their Names:'</h2></label>
    </br>
    <input type="text" class="colorInput" v-on:input="bga.backgroundColor = $event.target.value" placeholder="here...">
    </br>
    <input type="text" class="colorInput"  v-on:input="bgb.backgroundColor = $event.target.value" placeholder="... and here!">
</div>
`
    ,

};

export default ColorPage
Run Code Online (Sandbox Code Playgroud)

这应该用于更改“容器” div和“顶部” div的颜色:

Index.html

    <div id="container" v-bind:style="bga">
        <div class="top" v-bind:style="bgb">
            <div id="app">
                <h1 id="vueHead">Vue routing</h1>
                <h2 class="menu">
                    <router-link to="/">Color</router-link>
                    <router-link to="/main">Main</router-link>
                    <router-link to="/settings">Settings</router-link>
                    <router-link to="/vue">Vue</router-link>
                </h2>

            </div>
        </div>
          <router-view></router-view>
    </div>
Run Code Online (Sandbox Code Playgroud)

Vue路由位于index.js中:

import MainPage from '../components/mainPage.js'
import ColorPage from '../components/colorPage.js'

const routes = [
    {path: '/', component: ColorPage},
    {path: '/main', component: MainPage},

];
const router = new VueRouter({
    routes // short for `routes: routes`
});

var vm = new Vue({
    el: '#container',
    router,
});
Run Code Online (Sandbox Code Playgroud)

Wil*_*ard 5

创建组件时,Vue的某些典型语法之间存在细微差异。例如,数据必须是一个函数

..
data: {
  reactive: true,
}
..
Run Code Online (Sandbox Code Playgroud)

在标准的Vue实例中,上述情况非常好。但是,当您创建组件时,数据属性需要是一个返回对象的函数:

..
data() {
  return { reactive: true }
}
..
Run Code Online (Sandbox Code Playgroud)

此外,您可以使用中的其他道具与中的其他属性一样data