2

我正在关注此CodePen,并尝试将其放入默认的 VueJS 2.0 Boilerplate 中。这就是我将文件拆分的方式:

App.vue
main.js
components/Transitions.vue
components/Controls.vue
components/Page.vue

我在让它运行时遇到了很大的问题。例如我的 App.vue 没有找到state. 这就是我在main.js中定义它的方式:

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

const state = {
    animations: ['fade', 'slide', 'slideUp', 'zoom', 'flipX', 'flipY'],
    view: 'slide'
}

new Vue({
  render: h => h(App),
  data() {
    return this.state
  }
}).$mount('#app')

这是我的App.vue

<template>
  <div id="app">
    <component :is="state.view">
      <h1>{{ state.view }}</h1>
    </component>
    <controls></controls>
  </div>
</template>

这将是我的控件:

<template id="controls">
<ul class="controls">
  <li v-for="(animation, index) in state.animations" v-bind:key="index" @click.prevent="setView(animation)" v-bind:class="{ 'active': animation === state.view }">
    {{ animation }}
  </li>
</ul>
</template>

<script>
export default {
  template: '#controls',

  methods: {
    setView(animation) {
      this.state.view = animation
    }
  }
}
</script>

..等等。不幸的是我得到:

[Vue warn]: data functions should return an object:
https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function

(found in <Root>) vue.runtime.esm.js:619
[Vue warn]: Property or method "state" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

found in

---> <App> at src/App.vue
       <Root> vue.runtime.esm.js:619
[Vue warn]: Error in render: "TypeError: this.state is undefined"

我在这里做错了什么?如何让这个东西运行?

4

2 回答 2

2

将数据属性附加到根实例不会使它们在所有后代组件中全局可用(这似乎是您所尝试的)。实际上有几种方法可以跨组件共享状态,包括Vuex全局事件总线(例如,使用$root.emit()and $root.on())。然而,另一个简单的解决方案是使用Vue.observable以及从共享文件中导出的mixin

stateMixin.js:

import { observable } from "vue";

const state = observable({
  animations: ["fade", "slide", "slideUp", "zoom", "flipX", "flipY"],
  view: "slide"
});

// a mixin that declares a data propety named `state`
export default {
  data() {
    return {
      state
    };
  }
};

然后,您可以将该文件导入到任何需要访问的组件中state

应用程序.vue:

import stateMixin from '@/stateMixin'

export default {
  mixins: [stateMixin],
  mounted() {
    console.log(this.state.view) // <-- stateMixin provides access to `state`
  }
}

Codesandbox 中 Codepen 的演示


另请注意,由于您要转换为单文件组件 (SFC),因此不应导出template属性。SFC 本身已经声明了模板,并且编译器知道默认使用它。

于 2020-02-21T02:00:06.440 回答
1

您可以state通过应用扩展运算符返回它,如下所示:

const state = {
    animations: ['fade', 'slide', 'slideUp', 'zoom', 'flipX', 'flipY'],
    view: 'slide'
}

new Vue({
  render: h => h(App),
  data() {
    return {...state} 
  }
}).$mount('#app')
于 2020-02-20T18:51:33.503 回答