簡體   English   中英

Vue中獲取組件標簽的內容

[英]Get content of component tag in Vue

我剛開始玩 Vue。 我想做這樣的事情:

<snippet name="Select From Table">
  SELECT *
  FROM database.table
</snippet>

並生成一個鏈接,單擊該鏈接會調用 function,該鏈接可以訪問 SQL。

我嘗試使用組件,但我不知道如何在點擊 function 中獲取 SQL 所以我可以使用它。 插槽看起來很有趣,但這似乎只在標簽內部起作用,而不在屬性中起作用。

謝謝!

如果你想抓取插槽的內容,你必須循環this.$slots.slotName然后得到你需要的innerText或innerHtml。

PS:正如@Terry 提到的,允許客戶端執行任何 SQL 命令將存在巨大的安全風險。

下面的演示

 Vue.component('v-test',{ template:` <div> <a @click.stop="addText()">{{current}}</a> </div> `, data () { return { current: 'Bla' } }, methods: { addText: function () { this.current += 'Bla' } } }) Vue.component('snippet',{ template:` <div style="border: 1px solid grey" @click="getHtml()"> <slot></slot> </div> `, methods: { getHtml: function () { alert(this.$slots.default && Object.values(this.$slots.default).map((item, index) => { return item.elm && (item.elm.wholeText || item.elm.innerText) }).join('\r\n')) } } }) new Vue ({ el:'#app' })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script> <div id="app"> <div class="container"> <snippet>Test SQL...</snippet> <br> <snippet><strong>Te<i>s<span>.</span></i>t</strong> SQL...</snippet> <br> <snippet><strong>Test<v-test></v-test></strong> SQL...</snippet> </div> </div>

另一種解決方案是使用ref

 Vue.component('v-test',{ template:` <div> <a @click.stop="addText()">{{current}}</a> </div> `, data () { return { current: 'Bla' } }, methods: { addText: function () { this.current += 'Bla' } } }) Vue.component('snippet',{ template:` <div style="border: 1px solid grey" @click="getHtml()" ref="test"> <slot></slot> </div> `, methods: { getHtml: function () { alert(this.$refs.test.innerText) } } }) new Vue ({ el:'#app' })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script> <div id="app"> <div class="container"> <snippet>Test SQL...</snippet> <br> <snippet><strong>Te<i>s<span>.</span></i>t</strong> SQL...</snippet> <br> <snippet><strong>Test<v-test></v-test></strong> SQL...</snippet> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM