Share 5 little knowledge about Vue, hope it will be helpful to you (2)

a8b40ea0e18f8cc7611d4c6fa36ce24b.jpeg

Hello everyone, in the last article "Share 5 little knowledge about Vue, I hope it will be helpful to you (1)" , today we will continue to share 5 little knowledge about Vue, I hope it will be helpful to you.

1. How to deeply monitor the content changes of the object array?

013b73729fb462f975ceb5244bc069eb.jpeg

We can use a watcher to deeply watch an array of objects and count changes using Vue.js.

For example, we can write:

app.vue

<template>
  <div id="app">
    <Person :person="person" v-for="person in people" :key="person.id"></Person>
  </div>
</template>
<script>
import Person from "@/components/Person";
export default {
  name: "App",
  components: {
    Person,
  },
  data() {
    return {
      people: [
        { id: 0, name: "Bob", age: 27 },
        { id: 1, name: "Frank", age: 32 },
        { id: 2, name: "Joe", age: 38 },
      ],
    };
  },
};
</script>

Person.view

<template>
  <div class="hello">
    <div class="person">
      {
    
    { p.name }}
      <input type="text" v-model="p.age" />
    </div>
  </div>
</template>
<script>
export default {
  name: "Person",
  props: {
    person: Object,
  },
  data() {
    return {
      p: {},
    };
  },
  watch: {
    p: {
      handler(newValue) {
        console.log(newValue.id);
        console.log(newValue.age);
      },
      deep: true,
    },
  },
  mounted() {
    this.p = { ...this.person };
  },
};
</script>

In App.vue we have a people array which is used to render the Person component using v-for.

We pass the person as the value of the person prop.

Then in Person, we added the props attribute to accept the person prop.

We have a p responsive property that we set in the mounted hook with a copy of person as its value.

In the p watcher in the watch attribute, we record the newValue value.

We set the deep option to true to let us watch for changes in the object.

In the template, we render p.name, and bind p.age as the input value of the text input.

Now, when we type in the text input, the p watcher should run and record the newValue.age value.

2. How to call a global custom function in a Vue.js component?

9186f6ef198cbad59ac647159d1d4d78.jpeg

We can create mixins to make helper functions globally available in Vue.js single-file components.

For example, we could write:

<template>
  <!--在HTML中展示capitalizedName这个计算属性-->
  <div id="app">
    {
    
    { capitalizedName }}
  </div>
</template>

<script>
// 引入Vue库
import Vue from "vue";

// 创建一个全局混入,添加了一个可以在任何组件中使用的方法capitalizeFirstLetter
Vue.mixin({
  methods: {
    // 这个方法的作用是将传入的字符串的首字母转化为大写
    capitalizeFirstLetter: (str) => str[0].toUpperCase() + str.slice(1),
  },
});

// 导出当前Vue组件
export default {
  // 组件名称
  name: "App",
  // 组件的data属性,定义了组件的内部状态
  data() {
    return {
      // 定义了一个名为name的状态,初始值为"james"
      name: "james",
    };
  },
  // 计算属性,这是根据组件状态或者其它计算属性派生出的值
  computed: {
    // capitalizedName计算属性,会调用我们在全局混入中定义的capitalizeFirstLetter方法,对name状态进行处理
    capitalizedName() {
      return this.capitalizeFirstLetter(this.name);
    },
  },
};
</script>

We create our own mixins by calling Vue.mixin and passing in an object.

This will create a global mixin, so it will automatically be available in all components.

In this object, we set the methods property, which is an object with some component methods.

It has a capitalizeFirstLetter method that takes a string and returns a string with the first letter capitalized.

Next, we return the responsive attribute name in the data method.

Then we create a computed property called capitalizedName which calls the capitalizeFirstLetter method in the mixin with this.name as a parameter and returns the processed result.

Next, we add capitalizedName to the template for rendering.

Finally, we see the result displayed as 'James'.

3. Using setTimeout in Vue.js

34f3929e01a4bfb6e4d3ea853145aa5b.jpeg

We can use an arrow function in Vue.js by passing it as an argument to setTimeout.

For example, we can write:

<template>
  <div id="app">
    <button @click="setShow">show</button>
    <p v-if="show">hello</p>
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      show: false,
    };
  },
  methods: {
    setShow() {
      setTimeout(() => {
        this.show = true;
      }, 2000);
    },
  },
};
</script>

We have a method called setShow that calls setTimeout and passes in an arrow function as the first argument that calls this.show with true.

The second parameter is the delay in milliseconds before running the first parameter's callback.

We have to use arrow functions to get the correct this value in the callback function.

This this should be the component instance, because arrow functions don't bind their this value.

We set setShow to the value of the @click directive to run it when the button is clicked.

So when we click on it, the div shows because show becomes true.

4. How to prevent the click event from bubbling to the parent element when the button is clicked?

9532b9a6036d6f2499f1268b231d55ba.png

When clicking on an element containing a button in Vue.js, we can use the self modifier to prevent the click event from bubbling up to the parent element.

For example, we could write:

<template>
  <div id="app">
    <div class="parent" @click.self="showAlert('parent clicked')">
      <span class="child" @click="showAlert('child1 clicked')">Child1</span>
      <span class="child" @click="showAlert('child2 clicked')">Child2</span>
      <span class="child" @click="showAlert('child3 clicked')">Child3</span>
    </div>
  </div>
</template>
<script>
export default {
  name: "App",
  methods: {
    showAlert(str) {
      alert(str);
    },
  },
};
</script>
<style scoped>
.parent {
  padding: 20px;
}
</style>

We add the self modifier on the outer div element, so that the click event will only be limited to the parent div.

When we click on each div or span element, the showAlert method will be run.

5. Scroll to an element with Vue.js

262b2aadb4d9879b4ee12693e36f9315.jpeg

Sometimes, we need to scroll to an element using Vue.js. In this article, we'll take a look at how to scroll to an element using Vue.js.

We can scroll to an element using Vue.js by assigning a reference to the element we want to scroll to. We can then call the scrollIntoView method on the element assigned to the reference to scroll to that element. For example, we can write:

<template>
  <div id="app">
    <button @click="scrollToElement">scroll to last</button>
    <p v-for="n of 100" :key="n" :ref="n === 100 ? 'last' : undefined">
      {
    
    { n }}
    </p>
  </div>
</template>
<script>
export default {
  name: "App",
  methods: {
    scrollToElement() {
      const [el] = this.$refs.last;
      if (el) {
        el.scrollIntoView({ behavior: "smooth" });
      }
    },
  },
};
</script>

We have a button called scrollToElement that calls this method. Then we have some p elements, where the last reference is assigned to the last p element. In the scrollToElement method, we use this.$refs.last to get the element assigned to the last reference by destructuring. Then we call el.scrollIntoView and use an object with a behavior property to change the scrolling behavior.

in conclusion

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of the article is not easy. If you like my sharing, please don’t forget to like and forward it, so that more people in need See. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/132331544