Vue组件及父子组件传值
链接:http://www.qianxingweb.com
1.组件简易总结:
组件总结: 1.若要传值与组件,则应用组件的Vue实例的data中需定义属性 2.组件中定义props接收传递过来的参数 3.组件中绑定参数的自定义指定为中横线写法,如v-bing:current-page 4.要想子组件传值给父组件,需要子组件中触发事件,通过事件想父组件传值,子组件传值给父组件方式为:methods中定义template要触发的事件, 在该方法中使用this.$emit(要出发的事件,要传递的数据),并在父组件的方法中定义监听的事件方法
2.组件注意事项:
1、组件接收参数通过v-bing:xxx-xxx自定义指令接收,示例的:pages绑定对应于组件的props对应的属性pages 2、组件的指令只能是中横线写法,对应组件中的驼峰法属性或方法
3、以下示例供自己参考:传值给props:pages对应totalPages,current-page对应props的currentPage,current-change-event对应$emit的currentChangeEvent
4、子组件触发的this.$emit('abc',xxxx)中的abc对应父组件中组件监听的@abc="父组件的接收方法",abc可以是驼峰法也可以是中横线定义方式
3、简单的分页组件效果示例:

4、简单的分页组件写法:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
li{
list-style: none;
display: inline-block;
margin: 1rem;
}
</style>
</head>
<body>
<div id="app" class="base">
<!--组建的使用-->
<el-page :pages="totalPages" :current-page="currentPage" @current-change-event="currentChange"></el-page>
</div>
<script src="assets/js/vue.js"></script>
<script>
//注册全局分页组件
Vue.component('el-page', {
data(){
return {
current: this.currentPage,
total: this.pages,
}
},
watch:{
pages(n){
return this.total = n
}
},
methods: {
//前一页
clickPrev(){
if (this.current > 1) {
this.current--;
}
},
//后一页
clickNext(){
if (this.current < this.total) {
this.current++;
}
},
//当前页
clickCurrent(i){
this.current = i;
},
currentChangeEvent(){
console.log("now page:",this.current);
this.$emit("current-change-event",this.current);
},
},
props: {
//总数,接收父组件传递的值
pages: {
type: Number,
default: 5
},
//当前页
currentPage: {
type: Number,
default: 1
},
},
//@click="currentChangeEvent" 点击div区域触发的时间
template: `
<div class="pagination" @click="currentChangeEvent">
<li class="disabled" v-if="current==1" @click.prevent="clickPrev"><span>«</span></li>
<li v-else @click.prevent="clickPrev"><a href="javascript:void(0);">«</a></li>
<li v-for="i in total" :class="current==i ? 'active' : ''">
<template v-if="current==i">
<span>{{i}}</span>
</template>
<template v-else>
<a href="javascript:void(0);" @click.prevent="clickCurrent(i)">{{i}}</a>
</template>
</li>
<li class="disabled" v-if="current==total" @click.prevent="clickNext"><span>»</span></li>
<li v-else @click.prevent="clickNext"><a href="javascript:void(0);">»</a></li>
</div>
`
});
var pageVue = new Vue({
el:"#app",
data:{
//总页数,组件要接收的数据
totalPages:10,
//当前页,组件要接收的数据
currentPage:2,
},
methods:{
//父组件监听子组件触发的时间,达到子组件传值父组件的目的
currentChange(current){
console.log('当前页',current);
this.currentPage = current;
}
}
});
</script>
</body>
</html>
链接:http://www.qianxingweb.com

浙公网安备 33010602011771号