设置全局参数,调用参数三种方法,阻止默认事件,阻止冒泡,capture捕获

设置全局参数 main.ts

 

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'

let app=createApp(App)

//在全局属性中添加属性方法
app.config.globalProperties.url="http://www.4399.com"

app.config.globalProperties.msg="abc";
app.config.globalProperties.show=(msg:any)=>{
    alert(msg)
}
app.use(router).mount('#app')

 

 

index.vue

<template>
    <!-- 直接引用全局属性 -->
    {{ msg }}
    <h1>{{ url }}</h1>
    <button @click="show(url)">显示网址</button>

    <button @click="showUrl">方法调用显示网址</button>
    <hr />

    <button :[attrName]="'button'">按钮</button>
    要绑定的属性名称:<input v-model="attrName" />
    <hr />
    <button @[eventName]="show">这是一个按钮</button>
    要绑定的事件名称:<input v-model="eventName" />

    <hr />
    <button @click="isShow = !isShow">{{ isShow ? "隐藏" : "显示" }}</button>
    <template v-if="isShow">
        <h1>受v-show影响</h1>
        <h1>受v-if影响</h1>

        <hr />
        <!-- capture捕获,默认从里到外渲染,加上capture后就会从外到里渲染 -->
        <div @click.capture="showInfo" style="width:200px;height:100px;background:yellow">
            <!-- stop阻止冒泡 -->
            <button @click-stop="showInfo">点我你试试</button>
            <!-- prevent阻止默认事件 -->
            <a href="www.baidu.com" @click.stop.prevent="showInfo">点我试试</a>
        </div>
        <hr />
        <!-- self点击在自己的元素上才触发响应事件,跟stop的属性差不多 -->
        <div @click.self="showInfo" style="width:200px;height:100px;background:yellow">
            <button @click="showInfo">点我你试试</button>
        </div>
    </template>
</template>



<script lang="ts">
import { getCurrentInstance } from 'vue';
import { ref } from 'vue'
export default ({
    //方法调用全局属性
    setup() {
        let globalProperties =
            getCurrentInstance()?.appContext.config.globalProperties;
        let isShow = ref(true);
        function showUrl() {
            globalProperties?.show(globalProperties.url);
        }
        let attrName = ref("title")
        let eventName = ref("click");
        let show = (e: any) => {
            console.log(eventName.value)
        }
        function showInfo() {
            console.log("事件触发了!")
        }
        return { showUrl, eventName, show, attrName, isShow, showInfo }
    },
    mounted(this: any) {
        //初始化调用全局默认属性
        this.show(this.url);
    }
})
</script>

 

posted on 2022-11-01 10:02  最帅爸爸  阅读(45)  评论(0)    收藏  举报