您的位置:首页 > Web前端 > Vue.js

vue组件递归

2020-08-26 21:06 597 查看

vue组件递归

组件递归的话可以用来做一些后台管理系统的导航列表页面 可以用于多级导航的布局,十分简单

首先是一个Tree组件的话

tree.vue

<template>
<div>
<div :style="indent">
{{title}}
</div>
</div>
</template>

<script>
export default {
name: "Tree",
props: {
title: String,
children: Array,
},
</script>

<style>

</style><template>
<div>
<span v-show="!ishow">
<icon name="xia"></icon>
</span>
</div>
</template>

<script>
export default {
name: "Tree",
props: {
title: String,
children: Array,
sj: Number,
ishow: true,
},
</script>

<style>

</style>

在页面中引入这个组件 并且在页面中定义还导航的数据列表 项目中的话一般是接口来获取的,这里我手动模拟一个

home.vue

<template>
<div>
//这里的title就是页面中标题,children就是定义的children
<Tree :title="list.title" :children="list.children"/>
</div>
</template>

<script>
import Tree from "../components/tree";
export default {
components: {
Tree,
},
data() {
return {
list: {
title: "后台管理系统",
children: [
{
title: "一级导航(1)",
children: [
{
title: "二级导航(1——1)",
children: [
{
title: "三级导航(1——1——1)",
},
{
title: "三级导航(1——1——2)",
},
{
title: "三级导航(1——1——3)",
},
],
},
{
title: "二级导航(1——2)",
},
],
},
{
title: "一级导航(2)",
children: [
{
title: "二级导航(2——1)",
},
{
title: "二级导航(2——2)",
},
],
},
{
title: "一级导航(3)",
children: [
{
title: "二级导航(3——1)",
children: [
{
title: "三级导航(3——1——1)",
},
{
title: "三级导航(3——1——2)",
},
{
title: "三级导航(3——1——3)",
},
],
},
{
title: "二级导航(3——2)",
},
],
},
],
},
};
},
};
</script>

<style>
</style>

重点来了,其实组件的递归呢就是利用组件调用组件来实现的

这时候让我们来看tree.vue页面

<template>
<div>
<div :style="indent">
{{title}}
</div>
<Tree
v-for="(item,index) in children"
:key="index"
:title="item.title"
:children="item.children"
></Tree>
//这里的Tree就是下面定义的name
</div>
</template>

<script>
export default {
name: "Tree",//组件调用组件还是与name有关写的
props: {
title: String,
children: Array,
},
</script>

<style>

</style><template>
<div>
<span v-show="!ishow">
<icon name="xia"></icon>
</span>
</div>
</template>

<script>
export default {
name: "Tree",
props: {
title: String,
children: Array,
},
</script>

<style>

</style>

就这样 就实现了组件之间的递归,十分简单 再美化页面以下就可以了

vue mixins的用法

混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项

不仅仅局限于方法 还可以是data的参数,这个包含性很大

首先新建一个mixins的js文件

var GetUserDataMixIn = {
data() {
return { msg: 'mixins' }
},
created: function () {
this.getData();
},
methods: {
getData: function () {
console.log("调用后台用户数据的方法");
}
}
};

export default GetUserDataMixIn;

页面中引入这个js并且注册下

<template>
<div>
<button @click="getData">{{msg}}</button>
</div>
</template>
<script>
import GetUserDataMixIn from '../mixins/mixin'
mixins:[GetUserDataMixIn],
</script>

点击按钮输出结果“调用后台用户数据的方法“按钮文字为”mixins“

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: