我正在关注这个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://v2.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://v2.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"
我在这里做错了什么?如何让这个东西运行?
最佳答案
将数据属性附加到根实例并不会使它们在所有后代组件中全局可用(这似乎是您所尝试的)。实际上有几种方法可以跨组件共享状态,包括 Vuex或global event bus (例如,使用 $root.emit()
和 $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
};
}
};
然后,您可以将该文件导入到任何需要访问状态
的组件中:
App.vue:
import stateMixin from '@/stateMixin'
export default {
mixins: [stateMixin],
mounted() {
console.log(this.state.view) // <-- stateMixin provides access to `state`
}
}
demo of that Codepen in Codesandbox
另请注意,由于您要转换为单文件组件 (SFC),因此不应导出 template
属性。 SFC 本身已经声明了模板,并且编译器知道默认情况下使用它。
关于vue.js - 如何将CodePen拆分成webpacked组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60326677/