新建index.html,直接复制以下代码,双击浏览器运行即可。代码包含Vue的组件使用,可对照练习。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue组件</title>
<!--<script src="./vue.js"></script>-->
<!-- 开发环境版本,包含了有帮助的命令行警告 -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="root">
<h1>todoList</h1>
<input v-model="inputValue" placeholder="请输入内容"/>
<button @click="handleSubmit">提交</button>
<ul>
<li v-for="(item,index) in list" :key="index">{{item}}</li>
</ul>
<h1>全局组件 todo-item</h1>
<ul>
<todo-item v-for="(item,index) in list" :key="index"
:content="item"
:index="index"
@delitem="doDelItem"
></todo-item>
</ul>
<h1>全局组件</h1>
<my-p></my-p>
<h1>局部组件</h1>
<my-h2></my-h2>
</div>
<script>
//全局组件
Vue.component('my-p',{
template:'<p>我是一个P标签</p>'
})
//局部组件
var myH2={
template:'<h2>我是一个h2标签</h2>'
}
Vue.component('todo-item',{
props:['content','index'],
template:'<li>{{content}}<button @click="clickDelItem">删除当前项</button></li>',
methods:{
clickDelItem:function(){
this.$emit('delitem',this.index)
}
}
})
new Vue({
el:"#root",
components:{
'my-h2':myH2
},
data:{
inputValue:'',
list:[]
},
methods:{
handleSubmit:function(){
this.list.push(this.inputValue)
this.inputValue=''
},
doDelItem:function(index){
this.list.splice(index,1)
}
}
})
</script>
</body>
</html>
使用vue-cli开发,首先确保电脑上安装了node和npm
#全局安装 vue-cli
npm install --global vue-cli
#创建一个基于webpack 模板的新项目
vue init webpack your-project-name
cd your-project-name
npm run dev
文件结构
重复实现上述代码的功能,可以比较语法上的差异。
修改main.js
import Vue from 'vue'
import todoList from './todoList'
Vue.config.productionTip = false
new Vue({
el: '#app',
components: { todoList },
template: '<todoList/>'
})
在src文件夹下新建文件todoList.vue
<template>
<div>
<h1>todoList</h1>
<input v-model="inputValue" placeholder="请输入内容"/>
<button @click="handleSubmit">提交</button>
<ul>
<todo-item v-for="(item,index) in list" :key="index"
:content="item"
:index="index"
@delitem="doDelItem"
></todo-item>
</ul>
</div>
</template>
<script>
import todoItem from './components/itemList'
export default{
components:{
'todo-item':todoItem
},
data(){
return {
inputValue:'',
list:[]
}
},
methods:{
handleSubmit(){
this.list.push(this.inputValue)
this.inputValue=''
},
doDelItem(index){
this.list.splice(index,1)
}
}
}
</script>
<style scoped>
</style>
在src/components文件夹下新建文件itemList.vue
<template>
<div>
<li>{{content}}<button @click="clickDelItem">删除当前项</button></li>
</div>
</template>
<script>
export default{
props:['content','index'],
data(){
return {
}
},
methods:{
clickDelItem(index){
this.$emit('delitem',index)
}
}
}
</script>
<style scoped>
</style>