vue.js 2 从遗留前端迁移到单文件组件

vue.js 2 migrate from legacy frontend to single file component

所以,好吧,我会为此得到大量的反对票,但由于我还没有找到任何可用的答案,我认为值得一试。

我正在尝试尽可能顺利和不引人注目地将遗留应用程序迁移到 vue js。

我从一个没有任何其他子组件的简单组件开始。顺便说一句,我正在使用 webpack 进行构建。所以,我们开始吧。这是一个简单的 CRUD 表单。

没有 vue 父上下文,因为这将是这个遗留应用程序中的第一个 vue 组件。我已经走到这一步了:

import SinglePageVue from './single-page.vue';

// creating vue component
Vue.component('single-page-comp', SinglePageVue);

// invoke view by calling container
vue = new Vue({ el: '#component-container' });

// *** At this point I'd like to assign the data to the component
// somwhat like. Of course, this doesn't work, but this is what
// I'd like to do
vue.props.givenName = 'John'
vue.props.familyName = 'Doe'

还有一个提交事件,一旦提交表单,调用函数就需要响应该事件。

// in the script section this would look like

module.exports = {
  data: function() {
    return {
      onSubmit: function () {
        // assignable by function
      }
    }
  }
};

};

我该怎么做?

如果你想在 Vue 中更新组件的数据,有很多方法可以做到,但在这种情况下,我可能建议只创建一个传递给 Vue 实例的数据对象,它可以,再次将其传递给您的单页组件。

console.clear()

const SinglePageVue = {
  props:["sharedData"],
  template:`
    <div>
      <h1>{{sharedData.message}}</h1>
    </div>
  `
}
Vue.component("single-page-vue", SinglePageVue)

const sharedData = {
  message: "I'm shared data"
}

new Vue({
  el:"#app",
  data:{
    sharedData
  }
})

setTimeout(() => sharedData.message = "I was updated", 1000)
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
  <single-page-vue :shared-data="sharedData"></single-page-vue>
</div>

这里,sharedData 是您页面范围内的一个对象,您可以修改任何遗留代码。因为 sharedData 作为 Vue 的数据 属性 公开,它现在是反应式的,对其属性的更改将反映在使用它们的任何地方。

这基本上是一个超级简单的状态管理解决方案。如果你最终需要更多,你可能想研究 Vuex,但我已经用这种方法构建了几个 Vue 项目。