查看'导出默认'与'新视图'

问题描述 投票:54回答:4

我刚刚安装了Vue,并且一直在使用vue-cli webpack模板创建项目。当它创建组件时,我注意到它将我们的数据绑定在以下内容中:

export default {
    name: 'app',
    data: []
}

而在其他教程中,我看到绑定的数据:

new Vue({
    el: '#app',
    data: []
)}

有什么区别,为什么看起来两者之间的语法不同?我无法从我在vue-cli生成的App.vue中使用的标签内部获取“新Vue”代码。

vue.js vue-component vue-cli
4个回答
82
投票

当你声明:

new Vue({
    el: '#app',
    data () {
      return {}
    }
)}

这通常是应用程序其余部分来自的根Vue实例。这会挂掉html文档中声明的根元素,例如:

<html>
  ...
  <body>
    <div id="app"></div>
  </body>
</html>

另一种语法是声明一个可以在以后注册和重用的组件。例如,如果您创建单个文件组件,如:

// my-component.js
export default {
    name: 'my-component',
    data () {
      return {}
    }
}

您可以稍后导入它并使用它:

// another-component.js
<template>
  <my-component></my-component>
</template>
<script>
  import myComponent from 'my-component'
  export default {
    components: {
      myComponent
    }
    data () {
      return {}
    }
    ...
  }
</script>

另外,请务必将data属性声明为函数,否则它们不会被动反应。


3
投票

export default用于为Vue组件创建本地注册。

这是一篇很棒的文章,解释了有关组件https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e的更多信息


2
投票

第一种情况(export default {...})是ES2015语法,用于使某些对象定义可供使用。

第二种情况(new Vue (...))是用于实例化已定义对象的标准语法。

第一个将在JS中用于引导Vue,而其中任何一个都可用于构建组件和模板。

有关详细信息,请参阅https://vuejs.org/v2/guide/components-registration.html


-1
投票
<template>
  <my-components></my-components>
</template>
<script>
  import myComponents from 'my-components'
  export default {
    components: {
      myComponents
    }
    data () {
      return {}
    }
    created(){},
    methods(){}
  }
</script>
© www.soinside.com 2019 - 2024. All rights reserved.