vue组件化的应用

前言:vue组件化的应用涉及到vue-cli的内容,所以在应用之前是需要安装node和vue-cli的,具体如何安装我就不一一赘述了。可能一会儿我心情好的时候,可以去整理一下。

1、应用的内容:在一个页面中,需要一个固定的内容,这个内容可以多次引用,那么就可以考虑把他分离出来,在下次需要的时候,实现引用就好。

比如:

<input type="text" v-model="content" >
<button @click = addList>添加</button>
<ul>
      <li v-for="( item ) of todoList">{{item} 
      </li>
</ul>

通过输入框添加列表项,原本是这样的,但我可以考虑优化一下,把ul中的内容分离出去,再来引用它。作为一个简单的demo来学习。

2、父组件中给子组件命名,li-item

<input type="text" v-model="content" >
<button @click = addList>添加</button>
<ul>
      <li-item v-for='( item ,index) of todoList' :key = "index" :index="index" :content = 'item' @delete="deleteitem">
      </li-item>
</ul>

在组件中,必须有key值做索引,index值和content。

3、此时我们把分离的内容(子组件)写在一个新的叫LiItem的页面中。

<template>
    <li @click="deleteItem"> {{content}}</li>
</template>

<script>
export default {
  name: 'LiItem',
  props: ['content', 'index'],
  data () {
    return {
      item: 'item'
    }
  },
  methods: {
    deleteItem () {
      this.$emit('delete', this.index)
    }
  }
}
</script>

<style scoped>

</style>

子组件name,方便引用。子组件的值需要传在props中作为记录。在父组件中有需要调用。

4、然后在父组件中引入子组件的内容。

import LiItem from '@/components/LiItem'

在components里面加入子组件的值。

components: {
'li-item': LiItem
}

5、此时就分离出来了,如果还子组件上面还有相应的点击函数,那么就需要在子组件中定义。比如上面的代码中,有一个删除函数,即删除添加的选项deleteItem,方法需要在methods中定义。

deleteItem () {this.$emit('delete', this.index)}

然后在父组件中引入并实现功能

@delete="deleteitem"

deleteitem(){this.todoList.splice(this.item, 1)}

总结:这只是一种分离的方式,还有更多独立的更优化的方法,后期我会好好去探讨总结。

 
原文地址:https://www.cnblogs.com/zjingjing/p/9155703.html