Vue work development tips

1. Summary

​ This blog records some practical tips for Vue in daily development work, and will be added and updated in the future.

​ 1. Use Sass’s :global to define global styles.

​ 2. Use inside <style> to bind the attribute value to the attribute. v-bindCSS

​ 3. When passing values ​​between parent and child components, after using the .sync modifier, you can directly update the bindings in the parent component through $emit('update:propName') in the child component. certain data.

​ 4. Global variables can be declared in main.js through app.config.globalProperties.***.

​ 5. Render the HTML in the component to the specified DOM through the newly added <Teleport> built-in component in Vue3.

2. Content

1. Use Sass's :global to define global styles.

​ In the single-file component of Vue.js (.vue file), we usually use <style scoped> to add styles to the current component, so that the style is It will only affect the current component and will not affect other components. This is actually done by adding a unique attribute to each element (such as data-v-f3f3eg9), and then using this attribute in the style to select the element to achieve the local effect of the style.

​ But sometimes we may need to add some global styles in this style block. We can first use ::v-deep or >>> to perform deep selection, but this can only affect sub-components and sub-elements within the current component. And it cannot affect the same level or superior components and elements. If we need a truly global style, then we can use the :global tag to achieve it.

:global is a feature of CSS Modules that allows you to write global styles in modular CSS. In CSS modules, all class names are locally scoped by default, which means they are only valid in the current CSS file. But when you need to set some global styles, you can use the :global attribute. Add the attribute to the tag of the single-file component (.vue file), and Vue will treat this style block as a module ified CSS. If there is no scoped, then all styles will default to global styles, and will be meaningless. (So ​​if you write a separate , its internal styles will also be global styles~). <style>scoped:global<style>

In file A.vue:
<style lang="scss" scoped>
// 定义全局类名 其样式也变为全局样式
:global(.global-class) {
      
      
  color: red;
}
// 定义一个普通的局部样式 
.normal-class {
      
      
	// 使用 !important 提升优先级
	color: yellow!important;
}
</style>

In the B.vue file in the same directory as A.vue:
<!-- 类名 normal-class 位于后面  优先级更高 -->
<h1 class="global-class normal-class">测试:global全局样式</h1>
Page performance:

The element is only affected by global styles.global-class:

6f9ab40fd7fc4122b1ef73821bcda317

2. Use inside <style> to bind attribute values ​​to attributesv-bindCSS

​ In the single-file component of Vue.js (.vue file), if we want to dynamically modify the style of an element, the methods that can be adopted are: ① Set the inline style Style; ② Dynamically set class name. Now, I have discovered the third method. It turns out that the v-bind syntax sugar provided by Vue can be used directly inside <style> to bind the declared variables and implement With two-way binding, we only need to modify the variable value to dynamically modify the element style.

Note: The bound variable must be declared in data, otherwise it cannot be bound.

Usage syntax:
/* 变量名之前不需要加this */ 
css属性名: v-bind(变量名);
Specific case:
<template>
  <div>
    <h1>测试在style内部使用v-bind给CSS属性绑定属性值</h1>
  </div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      // 声明样式变量
      color: "red",
    };
  },
  mounted() {
      
      
    // 动态修改变量值
    setTimeout(() => {
      
      
      this.color = "blue";
    }, 2000);
  },
};
</script>

<style lang="scss" scoped>
h1 {
      
      
  font-size: 30px;
  /* 绑定样式变量 */
  color: v-bind(color);
}
</style>
Page effect:

initial:

Insert image description here

Two seconds later:

Insert image description here

3. When passing values ​​between parent and child components, after using the .sync modifier, you can directly update the binding in the parent component through $emit('update:propName') in the child component. The data.

Under normal circumstances, the data flow in Vue is one-way, that is, data is passed from the parent component to the child component. If the child component wants to modify the passed data, it can only pass the event to the parent component through $emit(), and then the parent component listens to the corresponding processing function of the binding, modifies the data after triggering, and then automatically updates the modified data. The data is passed to the subcomponent, and the data received by the subcomponent will be updated. This is too much trouble.

​ In order to simplify this process, Vue provides us with the .sync modifier to implement two-way binding between parent and child components. When the parent component passes values ​​to the child component, after using this modifier, we can directly update the data in the child component through $emit('update:propName'). This makes the code more concise and the logic clearer.

Parent component:
<template>
  <div>
    <h1>这是父组件{
   
   { count }}</h1>
    <!-- 向子组件传递数据并使用sync修饰符 -->
    <son :count.sync="count"></son>
  </div>
</template>

<script>
import son from "../components/son.vue";
export default {
      
      
  components: {
      
      
    son,
  },
  data() {
      
      
    return {
      
      
      count: 1,
    };
  },
};
</script>
Subassembly:
<template>
  <div>
    <h3 @click="add()">这是子组件{
   
   { count }}</h3>
  </div>
</template>

<script>
export default {
      
      
  props: {
      
      
    // 接收父组件传递过来的值
    count: {
      
      
      type: Number,
      default: 0,
    },
  },
  methods: {
      
      
    add() {
      
      
      // 子组件直接修改父组件传递的值
      this.$emit("update:count", this.count + 1);
    },
  },
};
</script>
Page effect:

Initial state:

Insert image description here

After clicking:

Insert image description here

4. Global variables can be declared in main.js through app.config.globalProperties.***.

​ If we want to define a variable in the project, the variable can be accessed in any global component. In addition to using Vuex, we can also use . This requirement is achieved by declaring global variables in /span>. Vue3 and later versions method, so it can only be used in . This method requires the use of Vue's main.jsapp.config.globalProperties.***createApp()

​ But please note that global variables defined through app.config.globalProperties do not support two-way binding, because this method only adds the variable to the prototype chain of the Vue instance, so that it can be used in the component. Global variables are accessed through the this keyword, so this method is suitable for situations where the variable value will basically not be changed after the initial definition, and two-way binding is not required.

The main.js file defines global variables:
// 导入createApp()函数
import {
    
     createApp } from 'vue'
// 导入App组件
import App from './App.vue'
// 创建App应用返回对应的实例对象
const app = createApp(App);
// 挂载全局变量
app.config.globalProperties.$overallObj = {
    
     value: 111, name: '全局对象' };
app.config.globalProperties.$overallString = '111全局字符串11111';
// 挂载实例对象
app.mount('#app')
In single file component (.vue file), call global variables:
<template>
  <div>
    <h1 @click="changeValue()">
      这个地方是调用的main.js中定义的全局字符串 --- {
   
   { this.$overallString }}
    </h1>
    <h1>这个地方是调用的main.js中定义的全局对象 --- {
   
   { this.$overallObj }}</h1>
  </div>
</template>

<script>
export default {
      
      
  methods: {
      
      
    changeValue() {
      
      
      console.log("修改前的全局字符串---", this.$overallString);
      console.log("修改前的全局对象---", this.$overallObj);
      this.$overallString = "我是改变后的全局字符串";
      this.$overallObj.name = "我是改变后的全局对象";
      console.log("修改后的全局字符串---", this.$overallString);
      console.log("修改后的全局对象---", this.$overallObj);
    },
  },
};
</script>
Page effect:

Initial effect:

Insert image description here

After the click event is triggered:

Insert image description here

5. Render the HTML in the component to the specified DOM through the newly added <Teleport> built-in component of Vue3.

​ In some cases, we want some content of the component not to be rendered at the location of the current component, but to be rendered under other DOM elements. The most common scenario is the implementation of the modal box pop-up component. We can set position: fixed; for the pop-up window to achieve full-screen display, but in this way, the style of the ancestor element must be restricted to built-in components. style attributes, so it is not very friendly. Vue3 provides us with a new implementation solution, which is or transform, perspectivefilter<Teleport>

<Teleport> is a new feature of Vue 3, used to transfer/move child nodes within a component to other locations in the DOM. <Teleport> Receives a to attribute to specify the destination of the transfer. The value of to can be a CSS selector string or a DOM element object. After setting up, after the page is rendered, you will find that the child nodes in the component are rendered under the target DOM element and become its child nodes. However <Teleport> the transferred to target must already exist in the DOM when mounting.

<Teleport> only changes the rendered DOM structure, it will not affect the logical relationship between components. <Teleport> The internal nodes can normally interact with the data in the component where they are located.

Component code:
<template>
  <div>
    <!-- 指定内部节点渲染到body元素下 -->
    <Teleport to="body">
      <h1>这个组件用来测试Teleport内置组件的作用</h1>
    </Teleport>
  </div>
</template>
Page effect:

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_45092437/article/details/134991900