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 = false

new 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'})

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

NotebookLM全新升级:Gemini 1.5 Pro助力全球研究与写作

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…

Python第二语言(九、Python第一阶段实操)

目录 1. json数据格式 2. Python与json之间的数据转换 3. pyecharts模块官网 4. pyecharts快速入门&#xff08;折线图&#xff09; 5. pyecharts全局配置选项 5.1 set_global_ops使用 5.1.1. title_opts 5.1.2 legend_opts 5.1.3 toolbox_opts 5.1.4 visualmap_opts…

L47---2706. 购买两块巧克力(排序)---Java版

1.题目描述 2.思路 &#xff08;1&#xff09;排序&#xff1a;从最便宜的巧克力开始组合 &#xff08;2&#xff09;双循环遍历所有可能的两块巧克力组合&#xff0c;计算其总花费。如果总花费小于等于 money&#xff0c;则更新最大剩余金额 &#xff08;3&#xff09;由于价…

度小满金融大模型的应用创新

XuanYuan/README.md at main Duxiaoman-DI/XuanYuan GitHub

jmeter性能优化之mysql监控sql慢查询语句分析

接上次博客&#xff1a;基础配置 多用户登录并退出jmx文件&#xff1a;百度网盘 提取码&#xff1a;0000 一、练习jmeter脚本检测mysql慢查询 随意找一个脚本(多用户登录并退出)&#xff0c;并发数设置300、500后分别查看mysql监控平台 启动后查看&#xff0c;主要查看mysql…

Linux安装MySQL教程【带图文命令巨详细】

巨详细Linux安装MySQL 1、查看是否有自带数据库或残留数据库信息1.1检查残留mysql1.2检查并删除残留mysql依赖1.3检查是否自带mariadb库 2、下载所需MySQL版本&#xff0c;上传至系统指定位置2.1创建目录2.2下载MySQL压缩包 3、安装MySQL3.1创建目录3.2解压mysql压缩包3.3安装解…

Ajax 快速入门

Ajax 概念&#xff1a;Ajax是一种Web开发技术&#xff0c;允许在不重新加载整个页面的情况下&#xff0c;与服务器交换数据并更新网页的部分内容。 作用&#xff1a; 数据交换&#xff1a;Ajax允许通过JavaScript向服务器发送请求&#xff0c;并能够接收服务器响应的数据。 异…

hustoj二开

目录 1、路径问题2、开发问题&#xff08;1&#xff09;、mysql&#xff08;2&#xff09;、php 啊啊啊啊&#xff01;&#xff01;&#xff01;难崩&#xff1a; 路径问题搞了好长时间才明白了该项目的路径如何设置的 >_< ,&#xff0c;本文就路径问题&#xff0c;前端页…

梯度提升决策树(GBDT)

GBDT&#xff08;Gradient Boosting Decision Tree&#xff09;&#xff0c;全名叫梯度提升决策树&#xff0c;是一种迭代的决策树算法&#xff0c;又叫 MART&#xff08;Multiple Additive Regression Tree&#xff09;&#xff0c;它通过构造一组弱的学习器&#xff08;树&am…

【C语言】轻松拿捏-联合体

谢谢观看&#xff01;希望以下内容帮助到了你&#xff0c;对你起到作用的话&#xff0c;可以一键三连加关注&#xff01;你们的支持是我更新地动力。 因作者水平有限&#xff0c;有错误还请指出&#xff0c;多多包涵&#xff0c;谢谢&#xff01; 联合体 一、联合体类型的声明二…

DDMA信号处理以及数据处理的流程---随机目标生成

Hello&#xff0c;大家好&#xff0c;我是Xiaojie&#xff0c;好久不见&#xff0c;欢迎大家能够和Xiaojie一起学习毫米波雷达知识&#xff0c;Xiaojie准备连载一个系列的文章—DDMA信号处理以及数据处理的流程&#xff0c;本系列文章将从目标生成、信号仿真、测距、测速、cfar…

RabbitMQ(五)集群配置、Management UI

文章目录 一、安装RabbitMQ1、前置要求2、安装docker版复制第一个节点的.erlang.cookie进入各节点命令行配置集群检查集群状态 3、三台组合集群安装版rabbitmq节点rabbitmq-node2节点rabbitmq-node3节点 二、负载均衡&#xff1a;Management UI1、说明2、安装HAProxy3、修改配置…

找出链表倒数第k个元素-链表题

LCR 140. 训练计划 II - 力扣&#xff08;LeetCode&#xff09; 快慢指针。快指针臂慢指针快cnt个元素到最后&#xff1b; class Solution { public:ListNode* trainingPlan(ListNode* head, int cnt) {struct ListNode* quick head;struct ListNode* slow head;for(int i …

Spring配置多数据库(采用数据连接池管理)

一&#xff0c;前言 大家在开发过程中&#xff0c;如果项目大一点就会遇到一种情况&#xff0c;同一个项目中可能会用到很多个数据源&#xff0c;那么这篇文章&#xff0c;博主为大家分享在spring应用中如何采用数据库连接池的方式配置配置多数据源。 本篇文章采用大家用的最…

音视频转为文字SuperVoiceToText

音视频转为文字SuperVoiceToText&#xff0c;它能够把视频或语音文件高效地转换为文字&#xff0c;它是基于最为先进的 AI 大模型&#xff0c;通过在海量语音资料上进行训练学习而造就&#xff0c;具备极为卓越的识别准确率。 不仅如此&#xff0c;它支持包括汉语、英语、日语…

Java Set系列集合的使用规则和场景(HashSet,LinkedHashSet,TreeSet)

Set集合 package SetDemo;import java.util.HashSet; import java.util.Iterator; import java.util.Set;public class SetDemo {public static void main(String[] args) {/*Set集合的特点&#xff1a;1.Set系列集合的特点&#xff1a;Set集合是一个存储元素不能重复的集合方…

如何下载BarTender软件及详细安装步骤

BarTender是美国海鸥科技推出的一款优秀的条码打印软件&#xff0c;应用于 WINDOWS95 、 98 、 NT 、 XP 、 2000 、 2003 和 3.1 版本&#xff0c; 产品支持广泛的条形码码制和条形码打印机&#xff0c; 不但支持条形码打印机而且支持激光打印机&#xff0c;还为世界知名品牌条…

Modbus主站和从站的区别

Modbus主站,从站 在工业自动化领域&#xff0c;Modbus是一种常用的通信协议&#xff0c;用于设备之间的数据交换。在Modbus通信中&#xff0c;主站和从站是两个关键的角色。了解主站和从站之间的区别对正确配置和管理Modbus网络至关重要。 Modbus主站的特点和功能 1.通信请求发…