vue2监听一个节点是否存在页面中

文章介绍了如何在Vue的mounted钩子函数中使用MutationObserver监听节点myNode是否存在于页面中,以及处理异步渲染的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以使用Vue的生命周期钩子函数mounted来监听一个节点是否存在页面中,代码如下:

<template>
  <div>
    <div ref="myNode"></div>
  </div>
</template>

<script>
export default {
  mounted() {
    // 监听myNode节点是否存在
    const observer = new MutationObserver((mutationsList) => {
      for (let mutation of mutationsList) {
        if (mutation.type === 'childList') {
          for (let node of mutation.addedNodes) {
            if (node === this.$refs.myNode) {
              console.log('myNode节点已存在');
            }
          }
        }
      }
    });

    observer.observe(this.$el, { childList: true });
  },
};
</script>

在上述代码中,我们首先在mounted钩子函数中创建了一个新的MutationObserver实例,该实例会监听当前组件的根节点this.$el的子节点的变化。当新增一个节点时,会遍历本次变化列表,寻找是否有新增的节点是我们所需的目标节点this.$refs.myNode,如果找到了,就表示该目标节点已经存在于页面中,这时我们可以做一些相关的操作。

需要注意的是,由于我们是在mounted钩子函数中监听节点变化的,因此该节点必须在组件mounted时已经渲染到了页面上才能被监听到。如果该节点是后续异步渲染的,可能需要使用$nextTick等方法,在节点被渲染到页面上后再进行监听。

### 使用 Vue 构建数据中台的数据流节点页面 #### 设计思路 构建一个高效且易于维护的数据中台前端界面,Vue.js 提供了强大的工具集来处理复杂的应用逻辑。为了实现数据流节点页面,可以采用组合式 API 和 Composition API 来管理状态和副作用。 #### 初始化项目结构 首先设置好项目的文件夹布局,确保有清晰的模块划分: ```plaintext src/ ├── assets/ # 静态资源目录 ├── components/ # UI组件存放位置 │ └── NodeItem.vue # 单个节点显示组件 ├── views/ # 页面级视图容器 │ └── DataFlowView.vue # 主要展示区域 └── store/ # Vuex仓库定义处 └── index.ts # 应用全局状态管理者 ``` #### 创建核心功能部件 ##### 定义基础模型和服务接口 在 `store/index.ts` 文件内声明应用所需的基础模型以及服务层方法,负责与后端交互并更新本地缓存中的业务对象实例。 ```typescript import { createStore } from 'vuex'; export default createStore({ state() { return { nodes: [], // 存储所有节点的信息 selectedNode: null, // 当前选中的节点ID }; }, mutations: { setNodes(state, payload) { state.nodes = payload; }, selectNode(state, nodeId) { state.selectedNode = nodeId; } }, actions: { async fetchNodes({ commit }) { try { const response = await axios.get('/api/nodes'); commit('setNodes', response.data); } catch (error) { console.error(error); } } } }); ``` ##### 制作可重用UI组件 开发名为 `NodeItem.vue` 的子组件用来表示单个数据流动单元,并支持点击事件触发选择行为。 ```vue <template> <div :class="['node-item', isSelected && 'selected']" @click="handleClick"> {{ node.name }} </div> </template> <script lang="ts"> import { defineComponent, computed } from 'vue'; import { useStore } from '@/store'; export default defineComponent({ props: ['node'], setup(props) { const store = useStore(); function handleClick() { store.dispatch('selectNode', props.node.id); } const isSelected = computed(() => store.state.selectedNode === props.node.id); return { handleClick, isSelected }; } }); </script> <style scoped> /* 添加样式 */ .node-item { padding: .5em; } .selected { background-color: lightblue; } </style> ``` ##### 整合视图逻辑 最后,在主要视图组件 `DataFlowView.vue` 中引入上述创建好的元素,完成整个页面的功能组装工作。 ```vue <template> <section class="data-flow-container"> <h2>数据流节点列表</h2> <ul v-if="nodes.length > 0"> <li v-for="(node, idx) in nodes" :key="idx"> <NodeItem :node="node"/> </li> </ul> <!-- 显示更多关于选定节点的具体信息 --> <pre>{{ currentNodeDetails }}</pre> </section> </template> <script lang="ts"> import { defineComponent, onMounted, ref, watchEffect } from 'vue'; import { useStore } from '@/store'; import NodeItem from '../components/NodeItem.vue'; export default defineComponent({ name: "DataFlowView", components: { NodeItem }, setup() { const store = useStore(); let nodes = ref([]); let currentNodeDetails = ref(null); onMounted(async () => { await store.dispatch('fetchNodes'); // 加载初始数据[^4] nodes.value = store.state.nodes; // 监听当前被选中的节点变化情况 watchEffect(() => { const id = store.state.selectedNode; if (!id || !Array.isArray(nodes.value)) return; currentNodeDetails.value = nodes.value.find(n => n.id === id)?.details ?? ''; }); }); return { nodes, currentNodeDetails }; } }); </script> <style scoped> /* 设置整体外观 */ .data-flow-container h2 { margin-bottom: 1rem; } ul { list-style-type: none; padding-left: 0; } </style> ``` 此方案利用了 Vue 的响应机制[^3],使得每当用户选择了新的节点时,界面上都会自动反映出最新的详情内容;同时也实现了对多源数据的有效监控,保证了实时性和准确性。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值