vue2中的插槽使用以及Vuex的使用

插槽分为默认插槽,定名插槽还有作用域插槽

一.默认插槽,定名插槽

//app.vue
<template>
<div class="container"><CategoryTest title="美食" :listData="foods"><img slot="center" src="https://img2.baidu.com/it/u=381412217,2118678125&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt=""><a slot="footer" href="www.baidu.com">更多美食</a></CategoryTest><CategoryTest title="游戏" :listData="games"><ul slot="center"><li v-for="(item,index) in games" :key="index">{{item}}</li></ul><div class="foot" slot="footer"><a  href="www.baidu.com">单机游戏</a><a href="www.baidu.com">网络游戏</a></div></CategoryTest><CategoryTest title="电影" :listData="films"><iframe slot="center" height=498 width=510 src='https://player.youku.com/embed/XNTE4MDgwMTAzMg==' frameborder=0></iframe><template v-slot:footer><div class="foot"><a href="www.baidu.com">经典</a><a href="">热门</a><a href="">推荐</a><h4>欢迎前来观影</h4></div></template></CategoryTest>
</div>
</template>
<script>
import CategoryTest from './components/CategoryTest.vue'
export default({name:'App',components:{CategoryTest},data() {return {foods:['火锅','烧烤','小龙虾','牛排'],games:['红色警戒','炉石传说','模拟飞行','战地','cod'],films:['教父','楚门的世界','情书','末代皇帝']}},
})
</script>
<style scoped>
.container,.foot{display: flex;justify-content: space-around;
}
iframe{width: 80%;height: 50%;margin: 0 auto;
}
.foot h4{text-align: center;
}
</style>						
//categoryTest.vue
<template><div class="category"><h3>{{title}}分类</h3><!-- slot 定义一个插槽(挖个坑,等着组件的使用者进行填充) --><slot name="center">我是一个默认值,当使用者没有传递集体结构时,我会出现</slot><!-- 为slot命名name:定义一个具名插槽 --><slot name="footer">我是一个默认值,当使用者没有传递集体结构时,我会出现</slot></div>
</template><script>
export default {name:'CategoryTest',props:['title']
}
</script><style>.category{background-color: rgb(12, 207, 207);width: 300px;height: 300px;}.category h3{text-align: center;background-color: yellow;}img{width: 100%;}
</style>

 效果如图:

二. 作用域插槽

//app.vue
<template>
<div class="container"><CategoryTest title="游戏"><template scope="atguigu"><div><ul><li v-for="(g,index) in atguigu.games" :key="index">{{g}}</li></ul></div></template></CategoryTest><CategoryTest title="游戏"><template scope="atguigu"><div><ol><li style="color:red" v-for="(g,index) in atguigu.games" :key="index">{{g}}</li></ol><h4>{{atguigu.x}}</h4></div></template></CategoryTest>
</div>
</template>
<script>
import CategoryTest from './components/CategoryTest.vue'
export default({name:'App',components:{CategoryTest},
})
</script>
<style scoped>
.container,.foot{display: flex;justify-content: space-around;
}
iframe{width: 80%;height: 50%;margin: 0 auto;
}
.foot h4{text-align: center;
}
</style>
//categoryTest.vue
<template><div class="category"><h3>{{title}}分类</h3><slot :games="games" :x='msg'>我是默认内容</slot></div>
</template><script>
export default {name:'CategoryTest',props:['title'],data() {return {games:['红色警戒','炉石传说','模拟飞行','战地','cod'],msg:'时间啊,你是多么的美丽'}},
}
</script><style>.category{background-color: rgb(12, 207, 207);width: 300px;height: 300px;}.category h3{text-align: center;background-color: yellow;}img{width: 100%;}
</style>

 如图所示:

三.vuex

1.概念:专门在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件通信
2.什么时候使用Vuex

  • 多个组件依赖于同一状态
  • 来自不同组件的行为需要变更同一状态

 1.搭建vuex环境

// 该文件用于创建vuex中最为核心的store
import Vue from 'vue'
// 引入Vuex
import Vuex from 'vuex'
// 使用Vuex插件
Vue.use(Vuex)
// 创建并暴露store
const store= new Vuex.Store({// 准备actions--用于响应组件中的动作actions:{},
// 准备mutations--用于to操作数据(state)mutations:{},// 准备state--用于存储数据
state:{},
//准备action--用于异步操作数据  
})
export default store
2.在main.js中创建vm时传入store配置项
....
//引入store
import store from './store'
//创建vm
new Vue({el:'#app',render:h=>app,store
})

 如下是个案例:

2.求和案例vue版本

//app.vue
<template>
<div><count-add></count-add>
</div>
</template>
<script>
import CountAdd from "./components/CountAdd.vue"
export default({name:'App',components:{CountAdd},
})
</script>
<style scoped></style>
//coutadd.vue
<template><div><h1>当前求和为:{{sum}}</h1><select v-model="n"><option :value="1">1</option><option :value="2">2</option><option :value="3">3</option></select><button @click="increment">+</button><button @click="decrement">-</button><button @click="incrementOdd">当前求和为奇数再加</button><button @click="incrementWait">等一等再加</button></div>
</template><script>
export default {name:'CountAdd',data() {return {n:1,//用户选择的数字sum:0//当前的和}},methods: {increment(){this.sum+=this.n},decrement(){this.sum-=this.n},incrementOdd(){if(this.sum%2!=0){this.sum+=this.n}},incrementWait(){setTimeout(()=>{this.sum+=this.n})}},
}
</script><style scoped>button{margin-left:5px ;}
</style>

3.求和案例vuex版本

//main.js文件
import Vue from 'vue'
import App from './app.vue'
// 引入store
import store from './store/index'
// 关闭Vue的生产提示
Vue.config.productionTip = falsenew Vue({store,render: h => h(App),beforeCreate(){Vue.prototype.$bus=this}
}).$mount('#app')
//store.js文件
// 该文件用于创建vuex中最为核心的store
import Vue from 'vue'
import countOption from './count'
import PersonOption from './person'
// 引入Vuex
import Vuex from 'vuex'
// 使用Vuex插件
Vue.use(Vuex)
// 创建并暴露store
const store= new Vuex.Store({modules:{countAbout:countOption,personAbout:PersonOption}
})
export default store
//count.js文件
const countOption={namespaced:true,actions:{jiaOdd:function(context,value){console.log('action中的jiaOdd被调用了',value)if(context.state.sum%2){context.commit('JIA',value)}},jiaWait:function(context,value){console.log('action中的jiaWait被调用了',value)setTimeout(() => {context.commit('JIA',value)}, 500);},},mutations:{JIA(state,value){console.log('mutations中的JIA被调用了',value)state.sum+=value},JIAN(state,value){console.log('mutations中的JIAN被调用了',value)state.sum-=value},},state:{sum:0,//当前的和name:'绘梨',hobby:'爱看电影的',},getters:{bigSum(state){return state.sum*10}}
}
export default countOption
//person.js
import axios from 'axios'
import { nanoid } from 'nanoid'
const PersonOption={namespaced:true,actions:{add_personWang(context,value){if(value.personName.indexOf('王')===0){context.commit('add_person',value)}else{alert('添加的人名不姓王')}},addPersonServer(context){axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(Response=>{context.commit('add_person',{id:nanoid(),personName:Response.data})},error=>{alert(error.message)})}},mutations:{add_person(state,value){console.log('mutations中的add_person被调用了')state.personList.unshift(value)}},state:{personList:[{id:'001',personName:'电次'}]},getters:{firstPersonName(state){return state.personList[0].personName}}
}
export default PersonOption

在Visual Studio Code中工作区中:

我们有一个store命名的文件夹里面有:

  • person.js
  • count.js
  • index.js

4.​ (模块化设计)

//app.vue
<template>
<div><count-add></count-add><person-add></person-add>
</div>
</template>
<script>
import CountAdd from "./components/CountAdd.vue"
import personAdd from './components/personAdd.vue'
export default({name:'App',components:{CountAdd,personAdd},
})
</script>
<style scoped></style>
//countadd.vue
<template><div><h1>当前求和为:{{sum}}</h1><h1>{{hobby}}{{name}}</h1><h1>当前求和放大10倍为{{bigSum}}</h1><h1 style="color:red">person组件的总人数是:{{personList.length}}</h1><select v-model="n"><option :value="1">1</option><option :value="2">2</option><option :value="3">3</option></select><button @click="increment(n)">+</button><button @click="decrement(n)">-</button><button @click="incrementOdd(n)">当前求和为奇数再加</button><button @click="incrementWait(n)">等一等再加</button></div>
</template><script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {name:'CountAdd',data() {return {n:1,//用户选择的数字}},methods: {//借助mpaMutations生成对应的方法,方法中对调用commit求联系mutation...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),//借助mpaMutations生成对应的方法,方法中对调用commit求联系mutation// ...mapMutations(['JIA','JIAN'])需要将上面的函数名换成同名...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})// ...mapAction(['JIAOdd','JIANWait'])需要将上面的函数名换成同名},computed:{...mapState('countAbout',['sum','name','hobby']),...mapState('personAbout',['personList']),// 借助mapState生成计算属性,从state中读取数据(对象写法)// ...mapState({sum:'sum',hobby:'hobby',name:'name'}),// 借助mapState生成计算属性,从state中读取数据(数组写法)// ...mapState(['sum','name','hobby','personList']),// 借助mapGetters生成计算属性,从Getters中读取数据(对象写法)// ...mapGetters({bigSum:'bigSum'})// 借助mapGetter生成计算属性,从Getters中读取数据(数组写法)...mapGetters('countAbout',['bigSum'])}
}
</script><style scoped>button{margin-left:5px ;}
</style>
//personadd.vue
<template><div><h1>人员列表</h1><h1 style="color:red">count组件的求和为:{{sum}}</h1><h1>列表中第一个人的名字是{{firstPersonName}}</h1><input type="text" placeholder="请输入名字" v-model="name"><button @click="add">添加</button><button @click="addWang">添加一个姓王的人名</button><button @click="addPersonServer">添加一个人,名字随机</button><ul><li v-for="p in personList" :key="p.id">{{p.personName}}</li></ul></div>
</template><script>
import {nanoid} from 'nanoid'
import {mapState} from 'vuex'
export default {name:'personAdd',data() {return {name:''}},methods: {add(){const personObj={id:nanoid(),personName:this.name}this.$store.commit('personAbout/add_person',personObj)this.name=''},addWang(){const personObj={id:nanoid(),personName:this.name}this.$store.dispatch('personAbout/add_personWang',personObj)this.name=''},addPersonServer(){this.$store.dispatch('personAbout/addPersonServer')}},computed:{...mapState('personAbout',['personList']),...mapState('countAbout',['sum']),firstPersonName(){return this.$store.getters['personAbout/firstPersonName']}}
}
</script><style></style>

如图所示:

5.vuex模块化+命名空间

目的:让代码更加好维护,让多种数据分类更加明确

 步骤一:修改store.js

const countAbout={namespaced:true,//开启命名空间state:{},mutation:{},action:{},getters{}
}
const PersonAbout={namespaced:true,//开启命名空间state:{},mutation:{},action:{},getters{}
}const store=new Vuex.store({modules:{countAbout,personAbout}
})

开启命名空间后,组件中读取state数据

//方法一,自己直接读取
this.$sstre.state.personAbout.list
//方法二,借助mapState读取
...mapState('countAbout',['sum','name','hobby'])

组件中读取getters数据

//方法一,自己直接读取
this.$store.getters['personAbout/fistPersonName']
//方法二,借助mapGetter读取
...mapGetters('countAbout',['bigSum'])

开启命名空间后,组件中调用dispatch

//自己直接dispath
this.$store.dispath('personAbout/addPersonWang',person)
//借助mapAction
...mapAction('coutnAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

开启命名空间后,组件中调用commit

//自己调用
this.$store.commit('personAbout/add_person',person)
//借助mapMutation
...mapMutation('countAbout',{increment:'JIA'})

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/25212.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

使用 Python 和 Selenium 进行网络抓取

如果你今天的工作是从竞争对手的网站上抓取定价页面信息。你会怎么做&#xff1f;复制粘贴&#xff1f;手动输入数据&#xff1f;当然不行&#xff01;他们绝对会花费你超级多的时间&#xff0c;而且你可能会犯一些错误。 需要指出的是&#xff0c;Python已经成为最流行的数据…

使用 Qwen-Agent 将 8k 上下文记忆扩展到百万量级

节前&#xff0c;我们组织了一场算法岗技术&面试讨论会&#xff0c;邀请了一些互联网大厂朋友、今年参加社招和校招面试的同学。 针对大模型技术趋势、大模型落地项目经验分享、新手如何入门算法岗、该如何准备面试攻略、面试常考点等热门话题进行了深入的讨论。 汇总合集…

【力扣】 两个字符串的最小ASCII删除和

一、题目描述 给定两个字符串s1 和 s2&#xff0c;返回使两个字符串相等所需删除字符的 ASCII 值的最小和 。 示例 1: 输入: s1 "sea", s2 "eat" 输出: 231 解释: 在 "sea" 中删除 "s" 并将 "s" 的值(115)加入总和。 在 &…

C# 绘图及古诗填字

绘图 绘图的结果如下&#xff1a; 绘图部分主要使用了 Bitmap、Graphics 具体的函数是 MakeMap 入参说明 string bg : 背景图 Rectangle rect &#xff1a;绘图区域 int row_count &#xff1a;行数 int col_count &#xff1a;列数 string fn &#xff1a;保存到的文件 …

Unity Standard shader 修改(增加本地坐标裁剪)

本想随便找一个裁剪的shader&#xff0c;可无奈的是没找到一个shader符合要求&#xff0c;美术制作的场景都是用的都标准的着色器他们不在乎你的功能逻辑需求&#xff0c;他们只关心场景的表现&#xff0c;那又找不到和unity标准着色器表现一样的shader 1.通过贴图的透明通道做…

【Java 百“练”成钢】Java 基础:类和对象

Java 基础&#xff1a;类和对象 01.打印信息02.打印类的简单名称03.打印类的 ClassLoader04.获取类的方法05.获取类的Package06.创建一个对象数组07.计算圆的面积08.计算圆的周长09.创建具有私有访问修饰符的成员10.创建带访问修饰符的成员11.将对象作为参数传递12.通过类对象获…

oracle开发中常用的sql语句

在Oracle数据库的开发过程中&#xff0c;SQL&#xff08;结构化查询语言&#xff09;是不可或缺的。无论是进行数据查询、数据插入、更新还是删除&#xff0c;都需要使用到SQL语句。以下是一些在Oracle开发中常用的SQL语句示例。 1. 数据查询&#xff08;SELECT&#xff09; …

基于axios给请求添加token

基于axios封装 创建js文件 import axios from "axios"; import { baseURL } from ../utils/config.js //请求的地址 if (process.env.NODE_ENV development) {baseURL; } else {baseURL; }//创建自定义axios对象 const instance axios.create({baseURL,timeo…

Java基础-一文一答系列

文章目录 Java 中应该使用什么数据类型来代表价格?怎么将 byte 转换为 StringJava 中怎样将 bytes 转换为 long 类型?Java 中 操作符是线程安全的吗?a a b 与 a b 的区别3 * 0.1 0.3 将会返回什么? true 还是 false?Int 和 Integer 哪个会占用更多的内存?为什么 Jav…

关于智慧校园建设的几点建议

随着科技的迅猛发展&#xff0c;智慧校园建设已成为现代教育的重要组成部分&#xff0c;对于提升教育质量、改善学生学习环境具有重要意义。为此&#xff0c;我提出以下几点建议&#xff0c;以帮助智慧校园建设更加有效和可持续。 首先&#xff0c;应注重基础设施建设。智慧校园…

Anaconda3 下载安装卸载

1、下载 官网链接&#xff1a;Download Now | Anaconda Step1&#xff1a;进入官网 Anaconda | The Operating System for AI Step2&#xff1a;进入下载页面&#xff0c;选择要Anaconda软件安装包 2、安装 Step1: 点击 Anaconda3-2024.02-1-Windows-x86_64.exe 安装包进行安…

线控转向 0 -- 线控转向介绍和专栏规划

一、线控转向介绍 高阶自动驾驶核心部件&#xff1a;英创汇智线控转向解决方案 _北京英创汇智科技有限公司 (trinova-tech.com) 线控转向的系统组成详细介绍大家可以看上面这个链接&#xff1b;我这里也只从里面截取一些图片&#xff0c;简单说明。 1、结构组成 线控转向分为…

数据交换平台_08_activatemq 如何集成其他系统或应用

如何集成其他系统或应用 目录概述需求:设计思路实现思路分析1. **使用ActiveMQ的JMS API**:2.使用ActiveMQ的REST API拓展实现参考资料和推荐阅读Survive by day and develop by night. talk for import biz , show your perfect code,full busy,skip hardness,make a bette…

如何打造不一样的景区文旅VR体验馆项目?

近年来影院类产品迅速火爆&#xff0c;市面上的产品越来越多&#xff0c;投资者可以说是挑花了眼。为了助力投资者实现持续盈利&#xff0c;今天来给大家分析目前普乐蛙大爆新品悬空球幕飞行影院与其他5D/7D影院有哪些区别&#xff0c;给大家的创业投资之路避避雷~ 那我们正式开…

vue26:vue的环境搭建

vue环境安装配置 在点击上方链接前&#xff0c;注意&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01; 下方的红字&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&#xff01;&am…

计算机网络--应用层

计算机网络–计算机网络概念 计算机网络–物理层 计算机网络–数据链路层 计算机网络–网络层 计算机网络–传输层 计算机网络–应用层 1. 概述 因为不同的网络应用之间需要有一个确定的通信规则。 1.1 两种常用的网络应用模型 1.1.1 客户/服务器模型&#xff08;Client/Se…

【产品研发】NPDP价值作用概述

导读&#xff1a;本文结合个人实践和思考对NPDP的价值和作用做了概述说明&#xff0c;对于产品经理而言掌握NPDP的知识体系并且应用到实际工作中&#xff0c;这是非常有必要的。走出以往狭隘的产品研发工作认知&#xff0c;以开放心态学习国际化产品创新开发流程将极大提升产品…

【大学物理】期末复习双语笔记

3 vectors and scalar 20 damped harmonic motion,forced harmonic motion, superposition of SHM damped harmonic motion underdamped motion:欠阻尼 critical damped零界阻尼 over damped过阻尼 energy of damped harmonic motion application of damped oscillation:减震器…

5.组件间通信-$attrs(祖孙组件通信)

组件间通信-$attrs(祖孙组件通信) 父组件&#xff1a; <template><div class"father"><h3>父组件</h3><h4>a&#xff1a;{{a}}</h4><h4>b&#xff1a;{{b}}</h4><h4>c&#xff1a;{{c}}</h4><h4>…

链表翻转,写法和交换类似,但是需要pre cur 还有一个临时变量nxt记录下一个结点

递归反转单链表&#xff08;头插法反转部分链表 要弄pre cur 还有nxt&#xff08;临时变量保存下一个结点 P0指到需要修改的链表的前一个结点 class Solution {public ListNode reverseBetween(ListNode head, int left, int right) {ListNode dummynew ListNode(-1,head);L…