【问题标题】:Vuejs single file components mixed with normal componentsVuejs 单文件组件与普通组件混合
【发布时间】:2018-05-16 22:27:04
【问题描述】:

我正在尝试将 vuejs 单文件组件与正常样式的组件(不确定它们叫什么)混合在一起,我已经为这些组件开发了现有代码。

ma​​in.js

import Vue from 'vue'
import test from './test.vue'
import VueMaterial from 'vue-material'

Vue.use(VueMaterial)

new Vue({
  el: '#app',
  render: h => h(test, 
    {props: {
      testprop: 'ttttt'
    }
  }),
  data:{
    // /testprop: 'tytytytyty'
  }
})

test.vue

<template>
  <div>
    <my-component></my-component>
    <div>This is the first single page component</div>
  </div>
</template>

<script>
import MyComponent from '../src/components/MyComponent.js'
import TestTest from '../src/components/TestTest.vue'
  export default {
    name: 'MainApp',
    props: ['testprop'],
    components: {
            TestTest,
            MyComponent

    },
    mounted: function(){

    },
    computed:{
      returnProp: function(){
        return this.testprop
      }
    }
  }
</script>

<style lang="scss" scoped>
  .md-menu {
    margin: 24px;
  }
</style>

MyComponent.js 普通样式组件

window.Vue = require('Vue') //would give errors vue undefined if i dont't add this line
Vue.component('my-component', {
    name: 'my-component',
    template: '<div>Normal component</div>'
})

index.html

<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta content="width=device-width,initial-scale=1,minimal-ui" name="viewport">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic|Material+Icons">
    <link rel="stylesheet" href="https://unpkg.com/vue-material@beta/dist/vue-material.min.css">
    <link rel="stylesheet" href="https://unpkg.com/vue-material@beta/dist/theme/default.css">

    <title>vuematerial</title>
  </head>
  <body>
    <div id="app">
        <main-app :testprop="testprop"></main-app>
    </div>

    <script src="dist/build.js"></script>

  </body>
</html>

单文件组件和子单文件组件(此处未显示)显示正常。普通类型将显示为

<!--function (t,n,r,i){return Mt(e,t,n,r,i,!0)}-->

在生成的html中。

我还尝试在 main.js 文件中导入 MyComponent。 有任何想法吗?

我真的不想将所有现有组件转换为单个文件的组件:(

【问题讨论】:

  • 不是 100% 确定,但看起来很不错,值得一试。而不是window.Vue = ...import Vue from 'vue'
  • 尝试将 import Vue from 'vue' 添加到 MyComponent.js 文件。没有错误但仍将组件生成为
  • 好的,保持导入到位,因为这是导入它的正确方法,而不是弄乱窗口对象。

标签: vue.js vue-component vue-material


【解决方案1】:

根据docs,子组件是一个对象,而不是附加到 Vue 实例的东西(即Vue.component()),所以像这样声明你的组件:

MyComponent.js

export default {
    name: 'my-component',
    template: '<div>Normal component</div>'
}

如果您想保持MyComponent 的格式不变,那么您需要在new Vue 调用之前注册组件。

【讨论】:

  • 非常感谢,如此简单的更改,现在我希望我现有的代码可以正常运行。
  • 没问题,很高兴它有帮助:)
猜你喜欢
  • 2019-05-13
  • 2018-08-12
  • 2018-06-24
  • 2019-07-29
  • 2021-05-05
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
相关资源
最近更新 更多