菜单
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

Vue 教程

Vue 首页 Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue 为什么、如何以及设置 Vue 第一个 SFC 页面 Vue 组件 Vue Props Vue v-for 组件 Vue $emit() Vue Fallthrough 属性 Vue 作用域样式 Vue 本地组件 Vue 插槽 Vue v-slot Vue 作用域插槽 Vue 动态组件 Vue Teleport Vue HTTP 请求 Vue 模板引用 Vue 生命周期钩子 Vue Provide/Inject Vue 路由 Vue 表单输入 Vue 动画 Vue 动画 v-for Vue 构建 Vue Composition API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue 示例

Vue Examples Vue Exercises Vue Quiz Vue Server Vue Certificate

Vue Lifecycle Hooks

Vue 中的生命周期钩子是组件生命周期中的特定阶段,我们可以在其中添加代码执行操作。

生命周期钩子

每次组件达到生命周期的某个新阶段时,都会运行一个特定的函数,我们可以将代码添加到该函数中。这些函数被称为生命周期钩子,因为我们可以将我们的代码“钩入”该阶段。

组件拥有的所有生命周期钩子如下

  1. beforeCreate
  2. created
  3. beforeMount
  4. mounted
  5. beforeUpdate
  6. updated
  7. beforeUnmount
  8. unmounted
  9. errorCaptured
  10. renderTracked
  11. renderTriggered
  12. activated
  13. deactivated
  14. serverPrefetch

以下是这些生命周期钩子的示例。


“beforeCreate”钩子

beforeCreate 生命周期钩子发生在组件初始化之前,因此是在 Vue 设置了组件的数据、计算属性、方法和事件监听器之前。

beforeCreate 钩子可用于设置全局事件监听器,但我们应避免在 beforeCreate 生命周期钩子中尝试访问属于组件的元素,例如数据、观察者和方法,因为它们在该阶段尚未创建。

此外,尝试从 beforeCreate 生命周期钩子访问 DOM 元素没有意义,因为它们直到组件被 mounted 之后才创建。

示例

CompOne.vue:

<template>
    <h2>Component</h2>
    <p>This is the component</p>
    <p id="pResult">{{ text }}</p>
</template>

<script>
export default {
	data() {
		return {
			text: '...'
		}
	},
  beforeCreate() {
		this.text = 'initial text'; // This line has no effect
    console.log("beforeCreate: The component is not created yet.");
  }
}
</script>

App.vue:

<template>
  <h1>The 'beforeCreate' Lifecycle Hook</h1>
  <p>We can see the console.log() message from 'beforeCreate' lifecycle hook, but there is no effect from the text change we try to do to the Vue data property, because the Vue data property is not created yet.</p>
  <button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: false
    }
  }
}
</script>

<style>
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  background-color: lightgreen;
}
#pResult {
  background-color: lightcoral;
  display: inline-block;
}
</style>
运行示例 »

在上面的示例中,CompOne.vue 文件第 15 行无效,因为我们在该行尝试更改 Vue 数据属性中的文本,但 Vue 数据属性实际上尚未创建。另外,请记住打开浏览器控制台以查看第 16 行 console.log() 调用的结果。


“created”钩子

created 生命周期钩子发生在组件初始化之后,因此 Vue 已经设置了组件的数据、计算属性、方法和事件监听器。

我们应避免在 created 生命周期钩子中尝试访问 DOM 元素,因为直到组件被 mounted 之后才能访问 DOM 元素。

created 生命周期钩子可用于通过 HTTP 请求获取数据,或设置初始数据值。如下面的示例所示,数据属性 'text' 被赋予了初始值

示例

CompOne.vue:

<template>
    <h2>Component</h2>
    <p>This is the component</p>
    <p id="pResult">{{ text }}</p>
</template>

<script>
export default {
	data() {
		return {
			text: '...'
		}
	},
  created() {
		this.text = 'initial text';
    console.log("created: The component just got created.");
  }
}
</script>

App.vue:

<template>
  <h1>The 'created' Lifecycle Hook</h1>
  <p>We can see the console.log() message from 'created' lifecycle hook, and the text change we try to do to the Vue data property works, because the Vue data property is already created at this stage.</p>
  <button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: false
    }
  }
}
</script>

<style>
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  background-color: lightgreen;
}
#pResult {
  background-color: lightcoral;
  display: inline-block;
}
</style>
运行示例 »

“beforeMount”钩子

beforeMount 生命周期钩子发生在组件被 mounted 之前,也就是组件被添加到 DOM 之前。

我们应避免在 beforeMount 生命周期钩子中尝试访问 DOM 元素,因为直到组件被 mounted 之后才能访问 DOM 元素。

下面的示例表明我们尚无法访问组件中的 DOM 元素,CompOne.vue 文件第 11 行不起作用,并在浏览器控制台中产生错误

示例

CompOne.vue:

<template>
    <h2>Component</h2>
    <p>This is the component</p>
    <p ref="pEl" id="pEl">We try to access this text from the 'beforeMount' hook.</p>
</template>

<script>
export default {
  beforeMount() {
    console.log("beforeMount: This is just before the component is mounted.");
    this.$refs.pEl.innerHTML = "Hello World!"; // <-- We cannot reach the 'pEl' DOM element at this stage 
  }
}
</script>

App.vue:

<template>
  <h1>The 'beforeMount' Lifecycle Hook</h1>
  <p>We can see the console.log() message from the 'beforeMount' lifecycle hook, but the text change we try to do to the 'pEl' paragraph DOM element does not work, because the 'pEl' paragraph DOM element does not exist yet at this stage.</p>
  <button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: false
    }
  }
}
</script>

<style>
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  background-color: lightgreen;
}
#pEl {
  background-color: lightcoral;
  display: inline-block;
}
</style>
运行示例 »

“mounted”钩子

组件添加到 DOM 树后,会立即调用 mounted() 函数,我们可以将我们的代码添加到该阶段。

这是我们第一次可以处理与组件相关的 DOM 元素,例如使用 ref 属性和 $refs 对象,如下面的第二个示例所示。

示例

CompOne.vue:

<template>
  <h2>Component</h2>
  <p>Right after this component is added to the DOM, the mounted() function is called and we can add code to that mounted() function. In this example, an alert popup box appears after this component is mounted.</p>
  <p><strong>Note:</strong> The reason that the alert is visible before the component is visible is because the alert is called before the browser gets to render the component to the screen.</p>
</template>

<script>
export default {
  mounted() {
    alert("The component is mounted!");
  }
}
</script>

App.vue:

<template>
  <h1>The 'mounted' Lifecycle Hook</h1>
  <button @click="this.activeComp = !this.activeComp">Create component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: false
    }
  }
}
</script>

<style scoped>
  div {
    border: dashed black 1px;
    border-radius: 10px;
    padding: 20px;
    margin: 10px;
    width: 400px;
    background-color: lightgreen;
  }
</style>
运行示例 »

注意: mounted 阶段发生在组件被添加到 DOM之后,但在上面的示例中,alert() 在我们看到组件之前可见。原因是首先将组件添加到 DOM,但在浏览器渲染该组件到屏幕之前,会发生 mounted 阶段,alert() 变得可见并暂停浏览器渲染组件。

下面是一个可能更有用的示例:在表单组件挂载后将光标置于输入字段中,以便用户可以直接开始输入。

示例

CompOne.vue:

<template>
  <h2>Form Component</h2>
  <p>When this component is added to the DOM tree, the mounted() function is called, and we put the cursor inside the input element.</p>
  <form @submit.prevent>
    <label>
      <p>
        Name: <br>
        <input type="text" ref="inpName">
      </p>
    </label>
    <label>
      <p>
        Age: <br>
        <input type="number">
      </p>
    </label>
    <button>Submit</button>
  </form>
  <p>(This form does not work, it is only here to show the mounted lifecycle hook.)</p>
</template>

<script>
  export default {
    mounted() {
      this.$refs.inpName.focus();
    }
  }
</script>
运行示例 »

“beforeUpdate”钩子

每当组件数据发生变化时,就会调用 beforeUpdate 生命周期钩子,但在更新渲染到屏幕之前。beforeUpdate 生命周期钩子发生在 updated 生命周期钩子之前

beforeUpdate 钩子有一个特别之处,那就是我们可以对应用程序进行更改而不触发新的更新,这样可以避免出现无限循环。这就是为什么不应在 updated 生命周期钩子中更改应用程序的原因,因为使用该钩子会创建无限循环。只需查看此处下方第三个示例(红色部分)。

示例

beforeUpdate() 函数将一个 <li> 标签添加到文档中,以指示 beforeUpdate() 函数已运行。

CompOne.vue:

<template>
  <h2>Component</h2>
  <p>This is the component</p>
</template>

App.vue:

<template>
  <h1>The 'beforeUpdate' Lifecycle Hook</h1>
  <p>Whenever there is a change in our page, the application is 'updated' and the 'beforeUpdate' hook happens just before that.</p>
  <p>It is safe to modify our page in the 'beforeUpdate' hook like we do here, but if we modify our page in the 'updated' hook, we will generate an infinite loop.</p>
  <button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
  <ol ref="divLog"></ol>
</template>

<script>
export default {
  data() {
    return {
      activeComp: true
    }
  },
  beforeUpdate() {
    this.$refs.divLog.innerHTML += "<li>beforeUpdate: This happened just before the 'updated' hook.</li>";
  }
}
</script>

<style>
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  background-color: lightgreen;
}
</style>
运行示例 »

“updated”钩子

在我们的组件更新了 DOM 树之后,就会调用 updated 生命周期钩子。

示例

updated() 函数使用 console.log() 写入一条消息。每次页面更新时都会发生这种情况,在本例中,每次组件添加或移除时都会发生。

CompOne.vue:

<template>
  <h2>Component</h2>
  <p>This is the component</p>
</template>

App.vue:

<template>
  <h1>The 'updated' Lifecycle Hook</h1>
  <p>Whenever there is a change in our page, the application is updated and the updated() function is called. In this example we use console.log() in the updated() function that runs when our application is updated.</p>
  <button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: true
    }
  },
  updated() {
    console.log("The component is updated!");
  }
}
</script>

<style>
#app {
  max-width: 450px;
}
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  width: 80%;
  background-color: lightgreen;
}
</style>
运行示例 »

单击“添加/移除组件”按钮 10 次后,我们可以在浏览器控制台中看到结果

console screenshot

注意:我们在调用 updated 生命周期钩子时必须小心,不要修改页面本身,否则页面将一遍又一遍地更新,从而创建无限循环。

让我们尝试看看如果我们做的与上面注意事项所警告的完全一样会发生什么。页面会无限更新吗?

示例

updated() 函数将文本添加到段落中,这又会再次更新页面,并且该函数一遍又一遍地运行,形成一个无限循环。幸运的是,您的浏览器最终会停止这个循环。

CompOne.vue:

<template>
  <h2>Component</h2>
  <p>This is the component</p>
</template>

App.vue:

<template>
  <h1>The 'updated' Lifecycle Hook</h1>
  <p>Whenever there is a change in our page, the application is updated and the updated() function is called.</p>
  <p>The first change that causes the updated hook to be called is when we remove the component by clicking the button. When this happens, the update() function adds text to the last paragraph, which in turn updates the page again and again.</p>
  <button @click="this.activeComp = !this.activeComp">Add/Remove Component</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
  <div>{{ text }}</div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: true,
      text: "Hello, "
    }
  },
  updated() {
    this.text += "hi, ";
  }
}
</script>

<style>
#app {
  max-width: 450px;
}
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  width: 80%;
  background-color: lightgreen;
}
</style>
运行示例 »

当您在本地机器上以开发模式运行上面的代码时,Chrome 浏览器的控制台警告如下

screenshot browser console warning

“beforeUnmount”钩子

beforeUnmount 生命周期钩子在组件从 DOM 中移除之前被调用。

正如我们在下面的示例中看到的,我们仍然可以在 beforeUnmount 钩子中访问 DOM 中的组件元素。

示例

CompOne.vue:

<template>
  <h2>Component</h2>
  <p ref="pEl">Strawberries!</p>
</template>
  
<script>
export default {
  beforeUnmount() {
    alert("beforeUnmount: The text inside the p-tag is: " + this.$refs.pEl.innerHTML);
  }
}
</script>

App.vue:

<template>
  <h1>Lifecycle Hooks</h1>
  <button @click="this.activeComp = !this.activeComp">{{ btnText }}</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: true
    }
  },
  computed: {
    btnText() {
      if(this.activeComp) {
        return 'Remove component'
      }
      else {
        return 'Add component'
      }
    }
  }
}
</script>

<style scoped>
  div {
    border: dashed black 1px;
    border-radius: 10px;
    padding: 20px;
    margin: 10px;
    width: 400px;
    background-color: lightgreen;
  }
</style>
运行示例 »

“unmounted”钩子

组件从 DOM 中移除之后,就会调用 unmounted 生命周期钩子。

此钩子可用于例如移除事件监听器或取消计时器或间隔。

当组件被 unmounted 时,会调用 unmounted() 函数,我们可以将我们的代码添加到其中

示例

CompOne.vue:

<template>
  <h2>Component</h2>
  <p>When this component is removed from the DOM tree, the unmounted() function is called and we can add code to that function. In this example we create an alert popup box when this component is removed.</p>
</template>

<script>
export default {
  unmounted() {
    alert("The component is removed (unmounted)!");
  }
}
</script>

App.vue:

<template>
  <h1>Lifecycle Hooks</h1>
  <button @click="this.activeComp = !this.activeComp">{{ btnText }}</button>
  <div>
    <comp-one v-if="activeComp"></comp-one>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: true
    }
  },
  computed: {
    btnText() {
      if(this.activeComp) {
        return 'Remove component'
      }
      else {
        return 'Add component'
      }
    }
  }
}
</script>

<style scoped>
  div {
    border: dashed black 1px;
    border-radius: 10px;
    padding: 20px;
    margin: 10px;
    width: 400px;
    background-color: lightgreen;
  }
</style>
运行示例 »

注意: unmounted 阶段发生在组件被从 DOM 中移除之后,但在上面的示例中,alert() 在组件消失之前可见。原因是首先将组件从 DOM 中移除,但在浏览器将组件的移除渲染到屏幕之前,会发生 unmounted 阶段,alert() 变得可见并阻止浏览器显示组件的移除。


“errorCaptured”钩子

当子/后代组件中发生错误时,会调用 errorCaptured 生命周期钩子。

此钩子可用于错误处理、日志记录或向用户显示错误。

示例

CompOne.vue:

<template>
  <h2>Component</h2>
  <p>This is the component</p>
  <button @click="generateError">Generate Error</button>
</template>

<script>
export default {
  methods: {
    generateError() {
      this.$refs.objEl.innerHTML = "hi";
    }
  }
}
</script>

App.vue:

<template>
  <h1>The 'errorCaptured' Lifecycle Hook</h1>
  <p>Whenever there is an error in a child component, the errorCaptured() function is called on the parent.</p>
  <p>When the button inside the component is clicked, a method will run that tries to do changes to a $refs object that does not exist. This creates an error in the component that triggers the 'errorCaptured' lifecycle hook in the parent, and an alert box is displayed with information about the error.</p>
  <p>After clicking "Ok" in the alert box you can see the error in the browser console.</p>
  <div>
    <comp-one></comp-one>
  </div>
</template>

<script>
export default {
  errorCaptured() {
    alert("An error occurred");
  }
}
</script>

<style>
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  background-color: lightgreen;
}
</style>
运行示例 »

关于错误的更多信息也可以作为 errorCaptured() 函数的参数捕获,这些参数是

  1. 错误
  2. 触发错误的组件
  3. 错误源类型

在下面的示例中,这些参数在 errorCaptured() 函数中被捕获并写入控制台

示例

CompOne.vue:

<template>
  <h2>Component</h2>
  <p>This is the component</p>
  <button @click="generateError">Generate Error</button>
</template>

<script>
export default {
  methods: {
    generateError() {
      this.$refs.objEl.innerHTML = "hi";
    }
  }
}
</script>

App.vue:

<template>
  <h1>The 'errorCaptured' Lifecycle Hook</h1>
  <p>Whenever there is an error in a child component, the errorCaptured() function is called on the parent.</p>
  <p>Open the browser console to see the captured error details.</p>
  <div>
    <comp-one></comp-one>
  </div>
</template>

<script>
export default {
  errorCaptured(error,compInst,errorInfo) {
    console.log("error: ", error);
    console.log("compInst: ", compInst);
    console.log("errorInfo: ", errorInfo);
  }
}
</script>

<style>
#app > div {
  border: dashed black 1px;
  border-radius: 10px;
  padding: 10px;
  margin-top: 10px;
  background-color: lightgreen;
}
</style>
运行示例 »

“renderTracked”和“renderTriggered”生命周期钩子

当渲染函数被设置为跟踪或监控响应式组件时,renderTracked 钩子会运行。renderTracked 钩子通常在初始化响应式组件时运行。

当这种被跟踪的响应式组件发生更改并因此触发新的渲染时,renderTriggered 钩子会运行,以便屏幕用最新更改进行更新。

响应式组件是可以更改的组件。

渲染函数是 Vue 编译的函数,它跟踪响应式组件。当响应式组件发生更改时,会触发渲染函数并重新渲染应用程序到屏幕。

renderTrackedrenderTriggered 钩子用于调试,并且仅在开发模式下可用。

要查看 renderTrackedrenderTriggered 钩子中的 alert()console.log(),您必须将下面示例中的代码复制到您的计算机上,并在开发模式下运行该应用程序。

示例

CompOne.vue:

<template>
  <h2>Component One</h2>
  <p>This is a component.</p>
  <button @click="counter++">Add One</button>
  <p>{{ counter }}</p>
</template>
  
<script>
export default {
  data() {
    return {
      counter: 0
    }
  },
  renderTracked(evt) {
    console.log("renderTracked: ",evt);
    alert("renderTracked");
  },
  renderTriggered(evt) {
    console.log("renderTriggered: ",evt)
    alert("renderTriggered");
  }
}
</script>

App.vue:

<template>
  <h1>The 'renderTracked' and 'renderTriggered' Lifecycle Hooks</h1>
  <p>The 'renderTracked' and 'renderTriggered' lifecycle hooks are used for debugging.</p>
  <p><mark>This example only works in development mode, so to see the hooks run, you must copy this code and run it on you own computer in development mode.</mark></p>
  <div>
    <comp-one></comp-one>
  </div>
</template>

<style scoped>
  div {
    border: dashed black 1px;
    border-radius: 10px;
    padding: 20px;
    margin-top: 10px;
    background-color: lightgreen;
  }
</style>
运行示例 »

注意:上面的示例代码旨在复制并在开发模式下本地运行,因为 renderTrackedrenderTriggered 钩子仅在开发模式下可用。


“activated”和“deactivated”生命周期钩子

如本页上方所示,我们有 mountedunmounted 生命周期钩子用于在组件从 DOM 中移除或添加到 DOM 时。

activateddeactivated 生命周期钩子用于缓存的动态组件添加或移除时,但不是从 DOM 中移除。<KeepAlive> 标签用于下面的示例以缓存动态组件。

示例

CompOne.vue:

<template>
  <h2>Component</h2>
  <p>Below is a log with every time the 'mounted' or 'activated' hooks run.</p>
  <ol ref="olEl"></ol>
  <p>You can also see when these hooks run in the console.</p>
</template>
  
<script>
export default {
  mounted() {
    console.log("mounted");
    const liEl = document.createElement("li");
    liEl.innerHTML = "mounted";
    this.$refs.olEl.appendChild(liEl);
  },
  activated() {
    console.log("activated");
    const liEl = document.createElement("li");
    liEl.innerHTML = "activated";
    this.$refs.olEl.appendChild(liEl);
  }
}
</script>

<style>
  li {
    background-color: lightcoral;
    width: 5em;
  }
</style>

App.vue:

<template>
  <h1>The 'activated' Lifecycle Hook</h1>
  <p>In this example for the 'activated' hook we check if the component is cached properly with <KeepAlive>.</p>
  <p>If the component is cached properly with <KeepAlive> we expect the 'mounted' hook to run once the first time the component is included (must be added to the DOM the first time), and we expect the 'activated' hook to run every time the component is included (also the first time).</p>
  <button @click="this.activeComp = !this.activeComp">Include component</button>
  <div>
    <KeepAlive>
      <comp-one v-if="activeComp"></comp-one>
    </KeepAlive>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: false
    }
  }
}
</script>

<style scoped>
  div {
    border: dashed black 1px;
    border-radius: 10px;
    padding: 20px;
    margin-top: 10px;
    background-color: lightgreen;
  }
</style>
运行示例 »

让我们扩展上面的示例,看看 activateddeactivated 钩子是如何工作的。我们还将使用 mountedunmounted 钩子,以便我们可以看到 mounted 钩子在缓存组件首次添加时运行一次,而 unmounted 钩子对于缓存组件永远不会运行。

示例

CompOne.vue:

<template>
  <h2>Component</h2>
  <p>Below is a log with every time the 'activated', 'deactivated', 'mounted' or 'unmounted' hooks run.</p>
  <ol ref="olEl"></ol>
  <p>You can also see when these hooks run in the console.</p>
</template>
  
<script>
export default {
  mounted() {
    this.logHook("mounted");
  },
  unmounted() {
    this.logHook("unmounted");
  },
  activated() {
    this.logHook("activated");
  },
  deactivated() {
    this.logHook("deactivated");
  },
  methods: {
    logHook(hookName) {
      console.log(hookName);
      const liEl = document.createElement("li");
      liEl.innerHTML = hookName;
      this.$refs.olEl.appendChild(liEl);
    }
  }
}
</script>

<style>
  li {
    background-color: lightcoral;
    width: 5em;
  }
</style>

App.vue:

<template>
  <h1>The 'activated' and 'deactivated' Lifecycle Hooks</h1>
  <p>In this example for the 'activated' and 'deactivated' hooks we also see when and if the 'mounted' and 'unmounted' hooks are run.</p>
  <button @click="this.activeComp = !this.activeComp">Include component</button>
  <div>
    <KeepAlive>
      <comp-one v-if="activeComp"></comp-one>
    </KeepAlive>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeComp: false
    }
  }
}
</script>

<style scoped>
  div {
    border: dashed black 1px;
    border-radius: 10px;
    padding: 20px;
    margin-top: 10px;
    background-color: lightgreen;
  }
</style>
运行示例 »

“serverPrefetch”生命周期钩子

“serverPrefetch”钩子仅在服务器端渲染 (SSR) 期间调用。

解释和创建“serverPrefetch”钩子的示例需要一个相对较长的介绍和设置,这超出了本教程的范围。


Vue 练习

通过练习来测试自己

练习

The  lifecycle hook is called 
just before a component is removed from the DOM.

开始练习



×

联系销售

如果您想将 W3Schools 服务用于教育机构、团队或企业,请发送电子邮件给我们
sales@w3schools.com

报告错误

如果您想报告错误,或想提出建议,请发送电子邮件给我们
help@w3schools.com

W3Schools 经过优化,旨在方便学习和培训。示例可能经过简化,以提高阅读和学习体验。教程、参考资料和示例会不断审查,以避免错误,但我们无法保证所有内容的完全正确性。使用 W3Schools 即表示您已阅读并接受我们的使用条款Cookie 和隐私政策

版权所有 1999-2024 Refsnes Data。保留所有权利。W3Schools 由 W3.CSS 提供支持