search
HomeWeb Front-endVue.jsHow to use setup and custom instructions in Vue3

setup syntactic sugar

The biggest advantage is that all declaration parts can be used directly without return.

Note: Some functions are not yet complete, such as: name and render need to be added separately. Tags are written according to the compositionAPI method

// You can also add <script></script>

setup syntactic sugar unique

<script setup>
import { ref ,reactive,toRefs } from &#39;vue&#39;
const a = 1;
const num = ref(99)  // 基本数据类型
const user = reactive({ // 引用数据类型
  age:11
})
// 解构能获取响应式属性 {}解构 toRefs保留响应式
const { age } = toRefs(user)
// 导出
defineExpose({
  a
})
// props
const props = defineProps({
  foo: String
})
// 事件
const emit = defineEmits([&#39;change&#39;, &#39;delete&#39;])
// 自定义指令
const vMyDirective = {
  created(el, binding, vnode, prevVnode) {
    // 下面会介绍各个参数的细节
    console.log(&#39;创建了&#39;)
  },
}
</script>

defineProps under setup defineEmits is related to the component application

// 子组件
<template>
  <div class="hello">
    <h2 id="nbsp-msg-nbsp">{{ msg }}</h2>
    <slot name="btn">
 
    </slot>
    <button @click="chickMe"></button>
  </div>
</template>
 
<script setup>
import { useSlots, useAttrs } from &#39;vue&#39;;
 
const slots = useSlots()
const attrs = useAttrs()
const props = defineProps({
  msg: String
})
const emit = defineEmits([&#39;change&#39;])
console.log(slots, attrs)
const chickMe = ()=>{
  emit(&#39;change&#39;,&#39;abc&#39;)
}
 
</script>
 
// 父组件
<template>
  <div class="home" >
    <HelloWorld msg="hello" atr="attrs" @change="changeP ">
      <template #btn>
        <div>我是 btn:{{ obj.text }}</div>
      </template>
    </HelloWorld>
  </div>
</template>
 <script setup>
import HelloWorld from &#39;../components/HelloWorld.vue&#39;;
import { ref ,reactive,toRefs } from &#39;vue&#39;
 const obj = reactive({
      id: 0,
      text: &#39;小红&#39;
    })
 const changeP=(e)=>{
      console.log(e)
    }
</script> 
、

defineExpose is related to the component application

// 子组件
<template>
  <div class="hello">
        123
  </div>
</template>
 
<script setup>
 
const testPose =()=>{
  console.log(&#39;子组件暴露方法&#39;)
}
defineExpose({
  testPose
})
</script>
 
// 父组件
<template>
  <div class="home" v-test>
    <HelloWorld  ref="helloSon"></HelloWorld>
    <button @click="testEpose"></button>
  </div>
</template>
<script setup>
import HelloWorld from &#39;../components/HelloWorld.vue&#39;;
import { ref } from &#39;vue&#39;
// setup函数的话可以从context上查找
const helloSon = ref(null);
const testEpose = () => {
  helloSon.value.testPose();
}
</script>

custom directive

  • created: in Called before the bound element's attribute or event listener is applied. This is useful when a directive needs to be appended to an event listener before the normal v-on event listener is called.

  • beforeMount: Called when the directive is bound to the element for the first time and before the parent component is mounted.

  • mounted: Called after the parent component of the bound element is mounted. Most of the custom instructions are written here.

  • beforeUpdate: Called before updating the VNode containing the component.

  • updated: Called after the containing component’s VNode and the VNodes of its subcomponents are updated.

  • beforeUnmount: Called before unmounting the parent component of the bound element

  • unmounted: When the directive is unbound from the element and the parent component has been unmounted , it is only called once.

import { createApp } from &#39;vue&#39;;
const Test = createApp();
Test.directive(&#39;my-directive&#39;, {
    // 在绑定元素的 attribute 前
    // 或事件监听器应用前调用
    created(el, binding, vnode, prevVnode) {
        // 下面会介绍各个参数的细节
        console.log(&#39;创建了&#39;)
    },
    // 在元素被插入到 DOM 前调用
    beforeMount(el, binding, vnode, prevVnode) { },
    // 在绑定元素的父组件
    // 及他自己的所有子节点都挂载完成后调用
    mounted(el, binding, vnode, prevVnode) { },
    // 绑定元素的父组件更新前调用
    beforeUpdate(el, binding, vnode, prevVnode) { },
    // 在绑定元素的父组件
    // 及他自己的所有子节点都更新后调用
    updated(el, binding, vnode, prevVnode) { },
    // 绑定元素的父组件卸载前调用
    beforeUnmount(el, binding, vnode, prevVnode) { },
    // 绑定元素的父组件卸载后调用
    unmounted(el, binding, vnode, prevVnode) { }
})
 
export default Test.directive(&#39;my-directive&#39;);
  • el: The element to which the directive is bound. This can be used to directly manipulate the DOM.

  • binding: An object containing the following properties.

    • value: The value passed to the directive. For example, in v-my-directive="1 1", the value is 2.

    • oldValue: The previous value, only available in beforeUpdate and updated. It is available whether the value changes or not.

    • arg: The arguments passed to the directive (if any). For example, in v-my-directive:foo, the parameter is "foo".

    • modifiers: An object containing modifiers (if any). For example, in v-my-directive.foo.bar, the modifier object is { foo: true, bar: true }.

    • instance: The component instance using this directive. dir: The definition object of the instruction.

  • vnode: Represents the underlying VNode of the bound element.

  • prevNode: The VNode representing the element to which the directive is bound in the previous rendering. Only available in beforeUpdate and updated hooks.

Application

<template>
  <div class="home" v-test>
  </div>
</template>
//setup 外部调用
<script>
// 指令必须 vXxx 这样书写
import vTest from &#39;./TestDirective&#39;
export default defineComponent({
   directives: {
      test:vTest,
    },
  setup(props) {
    // console.log(&#39;Test&#39;,vTest)
    
    return {
   
    };
  } 
})
</script>
//或者 setup内部
<script setup>
import vTest from &#39;./TestDirective&#39;
</script>

Object literal

<div v-demo="{ color: &#39;white&#39;, text: &#39;hello!&#39; }"></div>
 
app.directive(&#39;demo&#39;, (el, binding) => {
  console.log(binding.value.color) // => "white"
  console.log(binding.value.text) // => "hello!"
})

The above is the detailed content of How to use setup and custom instructions in Vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

Vue.js vs. React: Which Framework is Right for You?Vue.js vs. React: Which Framework is Right for You?May 01, 2025 am 12:21 AM

Vue.js is suitable for fast development and small projects, while React is more suitable for large and complex projects. 1.Vue.js is simple and easy to learn, suitable for rapid development and small projects. 2.React is powerful and suitable for large and complex projects. 3. The progressive features of Vue.js are suitable for gradually introducing functions. 4. React's componentized and virtual DOM performs well when dealing with complex UI and data-intensive applications.

Vue.js vs. React: A Comparative Analysis of JavaScript FrameworksVue.js vs. React: A Comparative Analysis of JavaScript FrameworksApr 30, 2025 am 12:10 AM

Vue.js and React each have their own advantages and disadvantages. When choosing, you need to comprehensively consider team skills, project size and performance requirements. 1) Vue.js is suitable for fast development and small projects, with a low learning curve, but deep nested objects can cause performance problems. 2) React is suitable for large and complex applications, with a rich ecosystem, but frequent updates may lead to performance bottlenecks.

Vue.js vs. React: Use Cases and ApplicationsVue.js vs. React: Use Cases and ApplicationsApr 29, 2025 am 12:36 AM

Vue.js is suitable for small to medium-sized projects, while React is suitable for large projects and complex application scenarios. 1) Vue.js is easy to use and is suitable for rapid prototyping and small applications. 2) React has more advantages in handling complex state management and performance optimization, and is suitable for large projects.

Vue.js vs. React: Comparing Performance and EfficiencyVue.js vs. React: Comparing Performance and EfficiencyApr 28, 2025 am 12:12 AM

Vue.js and React each have their own advantages: Vue.js is suitable for small applications and rapid development, while React is suitable for large applications and complex state management. 1.Vue.js realizes automatic update through a responsive system, suitable for small applications. 2.React uses virtual DOM and diff algorithms, which are suitable for large and complex applications. When selecting a framework, you need to consider project requirements and team technology stack.

Vue.js vs. React: Community, Ecosystem, and SupportVue.js vs. React: Community, Ecosystem, and SupportApr 27, 2025 am 12:24 AM

Vue.js and React each have their own advantages, and the choice should be based on project requirements and team technology stack. 1. Vue.js is community-friendly, providing rich learning resources, and the ecosystem includes official tools such as VueRouter, which are supported by the official team and the community. 2. The React community is biased towards enterprise applications, with a strong ecosystem, and supports provided by Facebook and its community, and has frequent updates.

React and Netflix: Exploring the RelationshipReact and Netflix: Exploring the RelationshipApr 26, 2025 am 12:11 AM

Netflix uses React to enhance user experience. 1) React's componentized features help Netflix split complex UI into manageable modules. 2) Virtual DOM optimizes UI updates and improves performance. 3) Combining Redux and GraphQL, Netflix efficiently manages application status and data flow.

Vue.js vs. Backend Frameworks: Clarifying the DistinctionVue.js vs. Backend Frameworks: Clarifying the DistinctionApr 25, 2025 am 12:05 AM

Vue.js is a front-end framework, and the back-end framework is used to handle server-side logic. 1) Vue.js focuses on building user interfaces and simplifies development through componentized and responsive data binding. 2) Back-end frameworks such as Express and Django handle HTTP requests, database operations and business logic, and run on the server.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.