我是Vue的初学者.js和我正在try 创建一个应用程序来满足我的日常任务,我遇到了Vue组件.下面是我try 过的,但不幸的是,它给了我这个错误:

vue.js:1023[Vue warn]:未知自定义元素:-是吗

有什么 idea 吗,请帮忙?

new Vue({
  el : '#app',
  data : {
    tasks : [
      { name : "task 1", completed : false},
      { name : "task 2", completed : false},
      { name : "task 3", completed : true}
    ]
  },
  methods : {
  
  },
  computed : {
  
  },
  ready : function(){

  }

});

Vue.component('my-task',{
  template : '#task-template',
  data : function(){
    return this.tasks
  },
  props : ['task']
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.js"></script>
<div id="app">
  <div v-for="task in tasks">
      <my-task :task="task"></my-task>
  </div>
  
</div>

<template id="task-template">
  <h1>My tasks</h1>
  <div class="">{{ task.name }}</div>
</template>

推荐答案

你忘了Vue initialization中的components部分.所以Vue实际上不知道你的组件.

将其更改为:

var myTask = Vue.component('my-task', {
 template: '#task-template',
 data: function() {
  return this.tasks; //Notice: in components data should return an object. For example "return { someProp: 1 }"
 },
 props: ['task']
});

new Vue({
 el: '#app',
 data: {
  tasks: [{
    name: "task 1",
    completed: false
   },
   {
    name: "task 2",
    completed: false
   },
   {
    name: "task 3",
    completed: true
   }
  ]
 },
 components: {
  myTask: myTask
 },
 methods: {

 },
 computed: {

 },
 ready: function() {

 }

});

这里是jsBin,所有这些似乎都正常工作:http://jsbin.com/lahawepube/edit?html,js,output

UPDATE

有时,您希望您的组件对其他组件全局可见.

在这种情况下,您需要在Vue initializationexport之前以这种方式注册组件(如果您想从另一个组件注册组件)

Vue.component('exampleComponent', require('./components/ExampleComponent.vue')); //component name should be in camel-case

在将组件添加到vue el中后:

<example-component></example-component>

Vue.js相关问答推荐

Vue路由路径匹配行为

VueI18n 无法读取或更改组合 API 中的区域设置

Vuejs 通过数据键迭代复杂对象

如何在FormKit中验证文本输入框中不能输入数字

Nuxt3-Vue中的useRoute和useRouter有什么区别

我可以在未注册的组件上构建 Vue.js 失败吗?

如何对对象数组进行 v-model

无法在 Vuex 中的其他操作中反跳操作

如何从特定索引呈现 v-for

Vuelidate 判断true/false

如何使 Rails 与 vue.js 一起工作?

Vue.js 如何计算总数?

vuex 中 { dispatch, commit } 的类型是什么?

如何从 .vue 文件中导出多个对象

从 Url 中删除查询字符串参数

动态注册本地 Vue.js 组件

为 Vue 组件动态添加属性

Vue JS 在渲染前等待数据

将登录页面包含在单页应用程序中是否不安全?

如何使用 Vue Test utils 测试输入是否聚焦?