gpt4 book ai didi

vue.js - 如何将CodePen拆分为Webpacked组件?

转载 作者:行者123 更新时间:2023-12-03 06:45:53 25 4
gpt4 key购买 nike

我正在关注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"

我在这里做错了什么?如何使这件事运行?

最佳答案

将数据属性附加到根实例并不能使它们在所有后代组件中全局可用(这似乎是您尝试的)。实际上,有几种方法可以在各个组件之间共享状态,包括Vuexglobal 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
};
}
};

然后,您可以将该文件导入到需要访问 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com