vue2 part3

vscode安装vue3 snippets

天气案例

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>姓名案例_插值语法实现</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!--准备好一个容器-->
    <div id="root">
        <h2>今天天气很{{info}}</h2>
        <!--  如果是今天天气很一般,按下按钮页面上没有体现,数据已经改变,但是开发者工具不更新 -->
        <button>切换天气</button>
        <button @click="changeWeather">切换天气</button><!-- 也可以,把methods删除即可 -->
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false//阻止vue在启动时生成生产提示。
    new Vue({
        el: '#root',
        data: {
            isHot: true
        },
        computed: {
            info() {
                return this.isHot ? '炎热' : '凉爽'
            }
        },
        methods: {
            changeWeather() {
                this.isHot = !this.isHot
            }
        }
    })
</script>
</html>

监视属性

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>姓名案例_插值语法实现</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!--准备好一个容器-->
    <div id="root">
        <h2>今天天气很{{info}}</h2>
        <!--  如果是今天天气很一般,按下按钮页面上没有体现,数据已经改变,但是开发者工具不更新 -->
        <button @click="changeWeather">切换天气</button><!-- 也可以,把methods删除即可 -->
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false//阻止vue在启动时生成生产提示。
    new Vue({
        el: '#root',
        data: {
            isHot: true
        },
        computed: {
            info() {
                return this.isHot ? '炎热' : '凉爽'
            }
        },
        methods: {
            changeWeather() {
                this.isHot = !this.isHot
            }
        },
        /*  watch: {
             ishot: {
                 handler(newVal, oldVal) {
                     console.log('newVal:', newVal, 'oldVal:', oldVal)
                 }
             }
         }, */
        vm.$watch('isHot', {
            immediate: true,
            handler(newVal, oldVal) {
                console.log('newVal:', newVal, 'oldVal:', oldVal)
            }
        })
    })
</script>
</html>

深度监视

023_尚硅谷Vue技术_深度监视_哔哩哔哩_bilibili

监视简写

当watch配置项只有handler时,可以开启简写形式:即不需要计算只需要响应hander

越简写,越乱,hhhh,总之大家记住一句话,vue管理的函数都别写箭头函数。以免this指向错误

watch和compute对比

这样来理解,对于软件底层来讲,方法、监控都是一样,但我们用架构思维给了做了不同的区分

计算属性能做的事,watch也能做但是watch能做的事,计算属性不一定能够做。

this没变,因为fullName里面的this指向的Vue,而定时器的this就是fullName中的this,陷入了一个误区,包一个定时器,fullName等一会就有返回值

025_尚硅谷Vue技术_watch对比computed_哔哩哔哩_bilibili

class和style绑定

class

026_尚硅谷Vue技术_绑定class样式_哔哩哔哩_bilibili

style

027_尚硅谷Vue技术_绑定style样式_哔哩哔哩_bilibili

条件渲染

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>条件渲染</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!--准备好一个容器-->
    <div id="root">
        <h1>当前的n值是:{{n}}</h1>
        <button @click="n++">点击n+1</button>
        <h2 v-show="false ">欢迎来到{{name}}</h2>
        <!-- v-show条件渲染,false条件为假时,h2标签将不会显示 -->
        <h2 v-if="true ">欢迎来到{{name}}</h2>
        <!-- v-if条件渲染,true条件为真时,h2标签将会显示 -->
        <!-- 这个要记一下的 ,两个隐藏的区别,面试偶尔会问到,v-show和v-if的区别,v-show是控制元素的显示隐藏,v-if是控制元素的渲染,当条件为真时才渲染,false时不渲染。 -->
        <div v-if="n===1">Angular</div>

        <div v-else-if="n===2">React</div>

        <div v-else-if="n===3">Vue</div>

        <div v-else>其它</div>
        <!-- 中间不允许打断 -->
        <template v-if="n===1">
            <h2>hello</h2>
            <h2>world</h2>
            <h2>vue</h2>
        </template><!-- template不影响结构,展示的时候结构没有破,只能v-if控制展示,v-show是错误的 -->
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false//阻止vue在启动时生成生产提示。

    new Vue({
        el: '#root',
        data: {
            name: '尚硅谷'
        }
    })
</script>

</html>

列表渲染

Js中一旦有顺序那么将会是使用数组保存数据   然后每一个对象可以保存一个完整详细的数据

:key="item.id" -> 主要是为了 diff 算法,尽量减少重新渲染的次数

记得key一定要写 有id用id 没id有索引!!!!

vue官网不推荐index,因为index不是数据的唯一标识,id才是

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>基本列表</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!--准备好一个容器-->
    <div id="root">
        <h2>人员列表</h2>
        <ul>
            <li v-for="p in persons" :key="p.id"><!-- key重要性,必须打标识 ,p of persons也可以-->
                {{ p.name }} - {{p.age}}
            </li>
        </ul>
        <h2>测试遍历字符串</h2>
        <ul>
            <li v-for="(char,index)of str" :key="index">
                {{ index }} - {{ char }}
            </li>
        </ul>
        <ul>
            <li v-for="(a,b) of 5">
                {{ a }} - {{ b }}
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false//阻止vue在启动时生成生产提示。

    new Vue({
        el: '#root',
        data: {
            persons: [
                { id: 1, name: '张三', age: 25 },
                { id: 2, name: '李四', age: 23 },
                { id: 3, name: '王五', age: 28 }
            ],
            car:{
                name:'宝马',
                price:100000,
                color:'红色'
            },
            str:"hello world"
        }
    })
</script>

</html>

key的作用

key就是一个标识,像身份证号码

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>基本列表</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!--准备好一个容器-->
    <div id="root">
        <h2>人员列表</h2>
        <button @click.once="addPerson">新增人员</button>
        <ul>
            <li v-for="(p, index) of persons" :key="index"> <!-- 由于页面重新渲染导致索引值重置 -->
                {{ p.name }} - {{p.age}}
                <input type="text">
            </li>
        </ul>

    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false//阻止vue在启动时生成生产提示。

    new Vue({
        el: '#root',
        data: {
            persons: [
                //我们把数据传给服务器,服务器把数据放在数据库里,数据库会生成id
                { id: 1, name: '张三', age: 25 },
                { id: 2, name: '李四', age: 23 },
                { id: 3, name: '王五', age: 28 }
            ]
        },
        methods: {
            addPerson() {
                const p = { id: '004', name: '李四', age: 26 }
                thispersons.unshift(p)//key的值可以是任意类型,但必须唯一
            }
        },
    })
</script>

</html>

修改为 <li v-for="(p, index) of persons" :key="p-id"> 因为id和后面的数据都是一一绑定死的,即使操作也不会出问题。但是index是活的,谁在第一位,谁的index就是0。本来张三的index是0,但是添加了老刘,所以现在老刘的index才是0

咱俩还一样,我就不再变啦:对比虚拟DOM,结果决定还是用之前的input

id存在于数据内部, 是唯一不变的, 而index随着数据的增加可能会导致改变

/ 1

                     自动缩放                     实际大小                     适合页面                     适合页宽                                          50%                     75%                     100%                     125%                     150%                     200%                     300%                     400%                   

面试题:react、vue中的key有什么作用?(key的内部原理)
1 .虚拟DOM中key的作用:
   key是虚拟DOM对象的标识,当数据发生变化时,Vue会根据【新数据】生成【新的虚拟DOM】,
随后Vue进行【新虚拟DOM】与【I日虚拟DOM】的差异比较,比较规则如下:
2 比较规则
(1) . 虚拟DOM中找到了与新虚拟DOM相同的key:
         ①•若虚拟DOM中内容没变,直接使川之前的真实DOM!
         ②.若虚拟DOM中内容变了,则生成新的真实DOM,随后替换掉页面中之前的真实DOM。
(2) .旧虚拟DOM中未找到与新虚拟DOM相同的key
        创建新的真实DOM,随后渲染到到页面。
3 •用index作为key可能会引发的问觊
        1 .若对数据进行:逆序添加、逆序删除等破坏联序操作:
        会产生没有必要的真实DOM更新==> 界面效果没问题,但效率低。
        2 .如果结构中还包含输入类的DOM:
        会产生错误DOM更断==> 界面有问凰
4.开发中如何选择key?:
        1 .最好使用每条数据的唯 标识作为key,比如id、手机号、身份证号、学号等唯•值.
        2 .如果不存在对数据的逆方添加、逆方删除等破坏敢序操作,仅用于渲染列表用于展示,
        使用index作为key是没有闷翘的.

列表过滤

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>基本列表</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!--准备好一个容器-->
    <div id="root">
        <h2>人员列表</h2>
        <input type="text" placeholder="请输入姓名" v-model="searchName">
        <ul>
            <li v-for="(p, index) of filPerson" :key="index">
                {{ p.name }} - {{p.age}}
            </li>
        </ul>

    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false//阻止vue在启动时生成生产提示。

    new Vue({
        el: '#root',
        data: {
            keyWord: '',
            persons: [
                { id: '001', name: '马冬梅', age: 18, sex: '女' },
                { id: '002', name: '周冬雨', age: 19, sex: '女' },
                { id: '003', name: '周杰伦', age: 20, sex: '男' },
                { id: '004', name: '温兆伦', age: 21, sex: '女' }
            ],
            filPerson: [],//
        },
        watch: {//computed能实现的,watch都能实现
            keyWord(val) {
                this.persons = this.persons.filter((p) => {
                    return p.name.indexOf(val) !== -1//indexOf方法用来查找字符串中是否存在子串,返回-1表示不存在,返回其他值表示存在。,
                })
                
            }
        }
    })
</script>

</html>

由于persons包含空字符串,所以搜索完毕后会出现所有的。即什么都没有-》正确结果-》所有结果,修改一下

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>基本列表</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!--准备好一个容器-->
    <div id="root">
        <h2>人员列表</h2>
        <input type="text" placeholder="请输入姓名" v-model="searchName">
        <ul>
            <li v-for="(p, index) of filPerson" :key="index">
                {{ p.name }} - {{p.age}}
            </li>
        </ul>

    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false//阻止vue在启动时生成生产提示。

    new Vue({
        el: '#root',
        data: {
            keyWord: '',
            persons: [
                { id: '001', name: '马冬梅', age: 18, sex: '女' },
                { id: '002', name: '周冬雨', age: 19, sex: '女' },
                { id: '003', name: '周杰伦', age: 20, sex: '男' },
                { id: '004', name: '温兆伦', age: 21, sex: '女' }
            ],
            filPerson: [],//
        },
        watch: {//computed能实现的,watch都能实现
            keyword: {
                immediate: true,
                Handle(val) {
                    this.persons = this.persons.filter((p) => {
                        return p.name.indexOf(val) !== -1//indexOf方法用来查找字符串中是否存在子串,返回-1表示不存在,返回其他值表示存在。,
                    })

                }
            }
        }
    })
</script>

</html>

computed看可以

列表排序

实际开发以后端排序为主,因为前端一次不可能请求所有数据,而用户想看到的排序一般都是所有数据的排序,所以通常由后端排序,数据库几十上百的数据,前端一次也就请求20条左右

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8" />
    <title>基本列表</title>
    <!-- 引入Vue -->
    <script type="text/javascript" src="../js/vue.js"></script>
</head>

<body>
    <!--准备好一个容器-->
    <div id="root">
        <h2>人员列表</h2>
        <input type="text" placeholder="请输入姓名" v-model="keyWord">
        <button @click="sortType=2">按年龄升序</button>
        <button @click="sortType=1">按姓名降序</button>
        <button @click="sortType=0">默认排序</button>
        <ul>
            <li v-for="(p, index) of filPerson" :key="index">
                {{ p.name }} - {{p.age}} - {{p.sex}}
            </li>
        </ul>

    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false//阻止vue在启动时生成生产提示。

    new Vue({
        el: '#root',
        data: {
            keyWord: '',
            sortType: 0,//0表示默认排序,1表示按姓名降序,2表示按年龄升序
            persons: [
                { id: '001', name: '马冬梅', age: 18, sex: '女' },
                { id: '002', name: '周冬雨', age: 19, sex: '女' },
                { id: '003', name: '周杰伦', age: 20, sex: '男' },
                { id: '004', name: '温兆伦', age: 21, sex: '女' }
            ]

        },
        computed: {
            filPerons() {
                const arr = this.persons.filter((p) => {
                    return p.name.indexOf(this.keyWord) !== -1
                })
                // 判断一下是否需要排序I
                if (this.sortType) {
                    arr.sort((p1, p2) => {
                        return this.sortType == 1 ? p2.age - p1.age : p1.age - p2.age
                    })
                }
                return arr
            }
        }
    })
</script>

</html>

vue监测的原理

033_尚硅谷Vue技术_更新时的一个问题_哔哩哔哩_bilibili这是一定导入

data里的数据在_data里,_data的数据要get name和set name来获取和修改,模板解析,生成新的虚拟DOM,新旧虚拟DOM对比,更新页面

无限递归

034_尚硅谷Vue技术_Vue监测数据的原理_对象_哔哩哔哩_bilibili这是模仿js写了vue 

给出了就是把obj的所有属性,通过forEach()转移到obs对象当中,然后二者通过get()和set()方法发生关联。

vue对set的监测

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>vue</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
        <hr/>
        <h2>学生名字:{{student.name}}</h2>
        <h2>学生性别:{{student.gender}}</h2><!-- vm里面没有也不报错,undefined在vue不显示-->
        <!-- <h2>学生性别:{{gender}}</h2>报错,因为不存在gender-->
        <h2>学生年龄:真实{{student.age.rAge}},对外{{student.age.sAge}}</h2>
        <h2>朋友</h2>
        <ul>
            <li v-for="f in student.friend" :key=" index">
                {{f.name}}--{{f.age}}
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示

    const vm = new Vue({
        el: '#root',
        data: {
            name: '尚硅谷',
            address: '北京市',
            student: {
                name: '张三',
                age: {
                    rAge: 20,
                    sAge: 18,
                },
                friend: [
                    { name: '李四', age: 21 },
                    { name: '王五', age: 22 },

                ]
            }
        }
    })
</script>

</html>

               简而言之,必须要在data对象里的属性才能被监听对象数据劫持,然后才能设置set方法来渲染界面

 可以使用Vue.set(target,key,val)来实现添加,如上面的代码             Vue.set(vm._data.student,'sex','男')

数据代理,通过数据代理,将属性移到vm实例对象中,就可vm.$set(vm.student,'sex','女')

vue.set有缺陷: 只能给vm的data里面的对象添加属性

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>vue</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
        <h2>校长是:{{leader}}</h2>
        <hr/>
        <h2>学生名字:{{student.name}}</h2>
        <button @click="addsex">添加一个性别属性 </button>
        <h2>学生性别:{{student.gender}}</h2><!-- vm里面没有也不报错,undefined在vue不显示-->
        <!-- <h2>学生性别:{{gender}}</h2>报错,因为不存在gender-->
        <h2>学生年龄:真实{{student.age.rAge}},对外{{student.age.sAge}}</h2>
        <h2>朋友</h2>
        <ul>
            <li v-for="(f, index) in student.friend" :key=" index">
                {{f.name}}--{{f.age}}
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示

    const vm = new Vue({
        el: '#root',
        data: {
            name: '尚硅谷',
            address: '北京市',
            student: {
                name: '张三',
                age: {
                    rAge: 20,
                    sAge: 18,
                },
                friend: [
                    { name: '李四', age: 21 },
                    { name: '王五', age: 22 },

                ]
            },
            methods:{
                addsex(){
                    this.$set(this.student,'gender','男')
                }
            }
        }
    })
</script>

</html>

vue对数组的监测

Vue.set(vm._data.student.hobby,1,'篮球')可以对数组改变,页面也更新,类似cpp的方法,一下搜到了 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>vue</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
    <div id="root">
        <h2>学校名称:{{name}}</h2>
        <h2>学校地址:{{address}}</h2>
        <h2>校长是:{{leader}}</h2>
        <hr />
        <h2>学生名字:{{student.name}}</h2>
        <button @click="addsex">添加一个性别属性 </button>
        <h2>学生性别:{{student.gender}}</h2><!-- vm里面没有也不报错,undefined在vue不显示-->
        <!-- <h2>学生性别:{{gender}}</h2>报错,因为不存在gender-->
        <h2>学生年龄:真实{{student.age.rAge}},对外{{student.age.sAge}}</h2>
        <h2>朋友</h2>
        <ul>
            <li v-for="(f, index) in student.friend" :key=" index">
                {{f.name}}--{{f.age}}
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示

    const vm = new Vue({
        el: '#root',
        data: {
            school: {
                name: '尚硅谷',
                address: '北京市'
            },
            student: {
                name: '张三',
                age: {
                    rAge: 20,
                    sAge: 18,
                },
                hobby: {
                    h1: '唱',//在控制台是没有h1h2的getter和setter的,修改不会触发页面更新
                    h2: '跳',//就是vm.student.hobby.h1 = '篮球'不会触发页面更新,只在控制台更新
                    h3: 'rap'
                },

                friend: [
                    { name: '李四', age: 21 },
                    { name: '王五', age: 22 },

                ]
            },  
            methods: {//vue重写了数组的方法,暂时未完工
                addsex() {
                    this.$set(this.student, 'gender', '男')
                }
            }
        }
    })
</script>

</html>

 代码未完工!!!!!

总结

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>vue</title>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
    <div id="root">
        <h1>学生信息</h1>
        <button @click="student.age++">年龄+1岁</button><br />
        <button @click="addSex">添加性别属性,默认值:男</button><br />
        <button @click="student.sex='未知'">修改性别</button><br />
        <button @click="addFriend">在列表首位添加一个朋友</button><br />
        <button @click="updataFirstFriendName">修改第一个朋友的名字为:张三</button><br />
        <button @click="addHobby">添加一个爱好</button><br />
        <button @click="drive">修改第一个爱好为:开车</button><br />
        <h3>姓名:{{student.name}}</h3>
        <h3>年龄:{{student.age}}</h3>
        <h3 v-if="student.sex">性别:{{student.sex}}</h3>
        <h3>爱好:</h3>
        <ul>
            <li v-for="(h,index) in student.hobby" :key="index">
                {{h}}
            </li>
        </ul>
        <h3>朋友们:</h3>
        <ul>
            <li v-for="(f,index) in student.friends" :key="index">
                {{f.name}}--{{f.age}}
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false;//阻止 vue 在启动时生成生产提示

    const vm = new Vue({
        el: '#root',
        data: {
            student: {
                name: 'tom',
                age: 18,
                hobby: ['抽烟', '喝酒', '烫头'],
                friends: [
                    { name: 'jerry', age: 35 },
                    { name: 'tony', age: 36 }
                ]
            }
        },
        methods: {
            addSex() {
                // Vue.set(this.student,'sex','男')
                this.$set(this.student, 'sex', '男')
            },
            addFriend() {
                this.student.friends.unshift({ name: 'jack', age: 70 })
            },
            updataFirstFriendName() {
                //this.student.friends[0]=123       error
                //不管对象在哪儿,数组里也行,改对象属性就能被检测到,但是数组没有属性,检测不到得用方法修改,所以不是下标问题,是看通过下标拿到了什么类型的数据
                this.student.friends[0].name = '张三'
            },
            addHobby() {
                this.student.hobby.push('看电影')
            },
            drive() {
                //this.student.hobby[0] = '开车'    error
                this.student.hobbysplice(0, 1, '开车')
                Vue.set(this.student.hobby, 0, '开车')//2种方法都可以
            }
        }
    })
</script>

</html>

Vue监视数据的原理:
1.vue会监视data中所有层次的数据。

2.如何监测对象中的数据?
通过setter实现监视,且要在new Vue时就传入要监测的数据。
(1).对象中后追加的属性,Vue默认不做响应式处理
(2).如需给后添加的属性做响应式,请使用如下API:
Vue.set(target,propertyName/index,value)或 
vm.$set(target,propertyName/index,value)

3。如何监测数组中的数据?
通过包裹数组更新元素的方法实现,本质就是做了两件事:
(1).调用原生对应的方法对数组进行更新。
(2).重新解析模板,进而更新页面。

4.在Vue修改数组中的某个元素一定要用如下方法:
1.使用这些API:push()、pop()、shift()、unshift()、splice()、sort()、reverse()
2.Vue.set()或 vm.$set()
特别注意:Vue.set()和vm.$set()不能给vm 或vm的根数据对象 添加属性!!!

filter可以增删改查,但是过滤怎么办?(放心filter在vue3里作废了,说明不是主流了)

上面的按钮
<button @click="removeSmoke">过滤掉所有吸烟的爱好</button>



vm加
<script>
removeSmoke() {
                this.student.hobby.filter((h)=>{
                    return h!='抽烟'//所有不是由Vue所控制的回调,尽可能的写成箭头函数,原因是箭头函数没有this会向上找,找到vm
                })  
            }
</script>

数据劫持就是数据已经交给vue来管了,操纵数据必须通过vue提供的方法来实现,数据劫持常用有三种:proxy,defineProperty,getter与setter:数据劫持描述的是过程,数据代理针对的是某个数据

  • 15
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 introduced the new feature called "Portal" which allows you to render a component's content in a different part of the DOM tree, outside of its parent component. This is particularly useful when you want to render a component's content in a different position within the DOM hierarchy. To use portals in Vue 3, you need to install the `@vue/portal-vue` package. You can do this by running the following command: ``` npm install @vue/portal-vue ``` Once installed, you can import the `Portal` component from the package and use it in your Vue components. Here's an example of how you can use portals: ```vue <template> <div> <button @click="togglePortal">Toggle Portal</button> <portal to="destination"> <p>This content will be rendered in a different part of the DOM tree.</p> </portal> <div id="destination"></div> </div> </template> <script> import { createApp } from 'vue'; import { createRouter, createWebHistory } from 'vue-router'; import { createSSRApp } from 'vue'; export default { name: 'MyComponent', methods: { togglePortal() { this.$portal.show('destination'); }, }, }; </script> ``` In this example, we have a button that toggles the visibility of the portal content. The portal content is wrapped inside the `<portal>` component and it has a `to` prop that specifies the ID of the destination DOM element where the content should be rendered. In this case, the destination element is a `<div>` with the ID "destination". When the button is clicked, the `togglePortal` method is called, which uses the `$portal` instance property to show or hide the portal content in the specified destination. Note that portals are particularly useful when you want to render modals, tooltips, or any other content that needs to be rendered outside of the current component's DOM hierarchy.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值