如何将 CodePen 拆分为 webpacked 组件?

How to split CodePen into webpacked Components?

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

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"

我在这里做错了什么?怎么把这个东西弄到运行?

您可以 return 通过应用扩展运算符 state 如下:

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

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

将数据属性附加到根实例不会使它们在所有后代组件中全局可用(这似乎是您尝试的)。实际上有几种方法可以跨组件共享状态,包括 Vuex or global event bus (e.g., using $root.emit() and $root.on()). However, another simple solution is to use Vue.observable along with a 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 本身已经声明了模板,编译器知道默认使用它。