当前位置:首页 > 技术 > 正文内容

Vue高级特性解析

访客 技术 2026年6月30日 5

1 计算属性应用

# 使用方法时,每次视图更新都会触发函数执行
# 通过计算属性实现属性级缓存优化

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>
</head>
<body>
<div id="app">
    <!--    <input type="text" v-model="name"> -&#45;&#45;》》 {{// name.slice(0, 1).toUpperCase() + name.slice(1)}}-->
    <input type="text" v-model="userName"> ---》》 {{capitalizeInput()}}

    <hr>
    <input type="text" v-model="userInput">--->{{capitalizedText}}
</div>
</body>

<script>
    const app = new Vue({
        el: '#app',
        data: {
            userName: '',
            userInput: ''
        },
        methods: {
            capitalizeInput() {
                // 视图更新时始终执行
                console.log('方法执行')
                return this.userName.charAt(0).toUpperCase() + this.userName.slice(1)
            }
        },
        computed: {
            capitalizedText() {
                // 仅当依赖数据变化时重新计算
                console.log('计算属性执行')
                return this.userInput.charAt(0).toUpperCase() + this.userInput.slice(1)
            }
        }
    })
</script>
</html>

计算属性过滤示例


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>

</head>
<body>
<div id="app">
    <h1>数据过滤演示</h1>
    <p><input type="text" v-model="searchQuery" placeholder="输入搜索内容"></p>
    - {{item}}


</div>
</body>
<script>
    const app = new Vue({
        el: '#app',
        data: {
            searchQuery: '',
            dataList: [
                'a',
                'at',
                'atom',
                'be',
                'beyond',
                'cs',
                'csrf',
                'd',
                'dddd',
            ],

        },
        computed: {
            filteredData() {
                return this.dataList.filter(item => item.includes(this.searchQuery))
            }
        }


    })
</script>
</html>

2 监听属性实践

# 监听特定属性变化并触发回调函数
    -

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>
</head>
<body>
<div id="app">
    <span> <button @click="category='人文'">人文</button>|<button @click="category='社科'">社科</button>|<button
            @click="category='地理'">地理</button></span>
    <br>
    {{currentCategory}}
</div>
</body>

<script>
    const app = new Vue({
        el: '#app',
        data: {
            currentCategory: '人文',
        },
        watch: {
            currentCategory(newVal) {
                console.log('分类变更至:', newVal)
                console.log('正在加载对应数据')
            }
        }
    })
</script>
</html>

3 组件开发基础

# 封装可复用UI模块,实现逻辑、样式、结构的统一管理
    -例如:可复用的轮播组件包含JS逻辑、CSS样式和HTML结构
    -组件化开发提升代码可维护性
    
# 组件类型
    -全局组件:可在任意位置注册使用
    -局部组件:仅在定义作用域内可用

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>

</head>
<body>
<div id="app">
    <h1>全局组件示例</h1>
    <custom-button></custom-button>
    <hr>
    局部组件
    <local-component></local-component>
    <hr>

</div>
</body>
<script>
    // 全局组件定义
    Vue.component('custom-button', {
        template: `
          <div>
          <button>返回</button>
          {{ message }}
          <button @click="triggerAction">继续</button>
          </div>`,
        data() {
            return {
                message: '操作提示'
            }
        },
        methods: {
            triggerAction() {
                alert('执行操作')
            }
        },
    })

    // 局部组件定义
    const localComponent = {
        template: `
          <div>
          <h1>局部组件</h1>
          {{ content }}
          <custom-button></custom-button>
          </div>`,
        data() {
            return {
                content: '组件内容'
            }
        },
        components: {
            'nested-component': {
                template: '<div>嵌套组件</div>'
            }
        }
    }

    new Vue({
        el: '#app',
        components: {
            localComponent
        }
    })
</script>
</html>

4 父子组件通信

1# 组件间数据隔离,需通过特定机制实现数据传递

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>

</head>
<body>
<div id="app">
    <h1>子组件数据传递</h1>
    父组件数据:{{parentData}}
    <hr>
    <child-component @custom-event="updateData"></child-component>
    <hr>

</div>
</body>
<script>


    const childComponent = {
        template: `
          <div>
          <h2>子组件</h2>
          <input type="text" v-model="inputValue"> ---》{{ inputValue }}
          <br>
          <button @click="sendData">传递数据</button>
          </div>`,
        data() {
            return {
                inputValue: ''
            }
        },
        methods: {
            sendData() {
                this.$emit('custom-event', this.inputValue)
            }
        }

    }

    new Vue({
        el: '#app',
        data: {
            parentData: '初始值'
        },
        methods: {
            updateData(value) {
                this.parentData = value
            }
        },
        components: {
            childComponent
        }


    })


</script>
</html>

5 子传父通信

自定义事件机制实现数据传递

6 ref引用

# ref属性用途
    -绑定DOM元素获取原生节点
    -绑定组件实例获取组件对象
        -可访问组件方法和属性
        -实现父子数据交互

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>

</head>
<body>
<div id="app">

    <h1>DOM引用示例</h1>
    <input type="text" ref="inputField" v-model="userInput">====>{{userInput}}
    <br>
    <button @click="printValue">打印值</button>
    <hr>
    <h1>组件引用示例</h1>
    <child-component ref="childRef"></child-component>


</div>
</body>
<script>


    const childComponent = {
        template: `
          <div>
          <button>返回</button>
          当前年龄--{{ age }}---{{ status }}
          <button @click="triggerAlert('迪丽热巴')">继续</button>
          </div>`,
        data() {
            return {
                status: true,
                age: 19
            }
        },
        methods: {
            triggerAlert(name) {
                alert(name)
            }
        }


    }

    new Vue({
        el: '#app',
        data: {
            userInput: '刘亦菲'
        },
        methods: {
            printValue() {
                // 访问DOM节点
                // this.$refs.inputField.value = '新值'
                console.log(this.$refs)
                // 访问组件实例
                // this.$refs.childRef.age = 999
                // this.$refs.childRef.status = false
                // this.$refs.childRef.triggerAlert()
                this.$refs.childRef.triggerAlert(this.userInput)
            }
        },
        components: {
            childComponent
        }


    })


</script>
</html>

7 动态组件切换

# 实现组件动态加载
# 示例:通过点击标签切换显示不同组件

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>

</head>
<body>
<div id="app">

    <div>
        <span @click="currentTab='home'">首页</span>|
        <span @click="currentTab='products'">商品</span>|
        <span @click="currentTab='orders'">订单</span>
    </div>
    <div>
        <component :is="currentTab"></component>
    </div>


</div>
</body>
<script>

    // 注册组件
    Vue.component('home', {
        template: '<div><h1>首页内容</h1></div>',
    })
    Vue.component('products', {
        template: '<div><h1>商品列表</h1><input type="text" placeholder="搜索商品"><button>搜索</button></div>',
    })
    Vue.component('orders', {
        template: '<div><h1>订单管理</h1></div>',
    })

    new Vue({
        el: '#app',
        data: {
            currentTab: 'home'
        },


    })

</script>
</html>

keep-alive缓存


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>

</head>
<body>
<div id="app">

    <div>
        <span @click="currentTab='home'">首页</span>|
        <span @click="currentTab='products'">商品</span>|
        <span @click="currentTab='orders'">订单</span>
    </div>
    <div>
        <keep-alive>
            <component :is="currentTab"></component>
        </keep-alive>
    </div>


</div>
</body>
<script>

    // 注册组件
    Vue.component('home', {
        template: '<div><h1>首页内容</h1></div>',
    })
    Vue.component('products', {
        template: '<div><h1>商品列表</h1><input type="text" placeholder="搜索商品"><button>搜索</button></div>',
    })
    Vue.component('orders', {
        template: '<div><h1>订单管理</h1></div>',
    })

    new Vue({
        el: '#app',
        data: {
            currentTab: 'home'
        },


    })

</script>
</html>

8 插槽机制


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="./js/vue.js"></script>

</head>
<body>
<div id="app">

    <h1>插槽使用示例</h1>
    <home-component>
        ![](https://tva1.sinaimg.cn/large/00831rSTly1gd1u0jw182j30u00u043b.jpg)
    </home-component>
    <hr>
    <home-component>
        <div>自定义内容</div>
    </home-component>
    <hr>

    <product-component>
        <div slot="footer">底部信息</div>
        <a href="" slot="header">查看美女</a>

    </product-component>

</div>
</body>
<script>

    Vue.component('home-component', {
        template: `
        <div>
        <button>返回</button>
           <span>首页</span>
         <button>前进</button>
         <hr>
         <slot></slot>
        </div>`,
    })

    Vue.component('product-component', {
        template: `
        <div>
        <slot name="header"></slot>
        <hr>
        <button>返回</button>
           <span>首页</span>
         <button>前进</button>
         <hr>
         <slot name="footer"></slot>
        </div>`,
    })

</script>
</html>

9 Vue项目构建

# Vue脚手架工具使用
# 支持Vue2/Vue3项目创建
    -基于Webpack构建
    -Vite新一代构建工具
    -Vue3推荐使用TypeScript开发
    
# 环境准备
    -安装Node.js运行时环境
        -JavaScript运行环境,包含文件/网络操作功能
        -官网:https://nodejs.org/zh-cn/download/
        -安装后获得node/npm命令
    
 # 模块管理
    -使用cnpm替代npm加速依赖安装
    -安装命令:cnpm install -g @vue/cli
    
 # 项目创建
    -vue create my-project
    
 # 开发工具
    -推荐使用VSCode或WebStorm
    -PyCharm配合Vue插件开发
    
 # 项目运行
    -npm run serve
    -或通过IDE运行
    
 # 依赖安装示例
    cnpm install axios

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。