问题
如何将我的变量添加到 My VueJS app那个使用 babel?
背景
我有一个使用 Vue 和 Axios 的应用程序。它工作正常,但我添加了动态重新格式化字符串的功能,重新格式化字符串的代码适用于 my pen工作正常。
var brewer = document.getElementsByClassName('author-raw');
for (var contrib = 0; contrib < brewer.length; contrib++) {
var matches = brewer[contrib].innerHTML.match(/(.*)\s\<([a-z]*)\>/);
var output = `${matches[1]} <a href="https://www.twitter.com/${matches[2]}" target="_blank">@${matches[2]}</a>`;
brewer[contrib].closest('div').querySelector('cite').innerHTML = output;
}
我现在需要将它添加到 my beer education app
我查看了 documentation for vue我想我需要将它添加到创建的 block 中?它在那里不起作用。
created() {
//code goes here?
}
在 React 中,我几乎可以在任何地方使用它。
编辑1
我忘了我应该转换成 ES6,所以更新的 JS 是
const brewer = document.getElementsByClassName('author-raw');
for (let contrib = 0; contrib < brewer.length; contrib++) {
const matches = brewer[contrib].innerHTML.match(/(.*)\s\<([a-z]*)\>/);
const output = `${matches[1]} <a href="https://www.twitter.com/${matches[2]}" target="_blank">@${matches[2]}</a>`;
brewer[contrib].closest('div').querySelector('cite').innerHTML = output;
}
最佳答案
我不会尝试以这种方式操作 DOM,而是操作数据。
将您的 addBeer
方法更改为:
addBeer() {
axios.get('https://api.punkapi.com/v2/beers/random')
.then(response => {
let api = response.data[0];
// parse contributor here
let contributor = api.contributed_by
let matches = contributor.match(/(.*)\s\<([a-z]*)\>/)
let apiInfo = {
name: api.name,
desc: api.description,
img: api.image_url,
tips: api.brewers_tips,
// and add both parts to your data
contributor: matches[1],
twitter: `@${matches[2]}`,
tagline: api.tagline,
abv: api.abv,
food: api.food_pairing
};
this.beers.push(apiInfo)
if (this.bottomVisible()) {
this.addBeer()
}
})
}
并更改模板以使用已解析的数据:
<span class="author-raw" aria-hidden="true">
{{ beer.contributor }}
<a style="color: white" :href="`https://www.twitter.com/${beer.twitter}`">{{beer.twitter}}</a>
</span>
这是您的 codepen updated .
使用 Vue,如果你开始操作 DOM,你几乎总是会做错,除非你试图与外部库集成。
另一种方法是编写一个小的功能组件。
const Contributor = {
functional: true,
render(h, context){
const {contributor} = context.props
// leave if there is no contributor
if (!contributor) return null
const parsed = contributor.match(/(.*)\s\<([A-Za-z]*)\>/)
// leave if we couldn't parse the contributor
if (!parsed || parsed.length < 2) return null
const [original, name, handle] = parsed
const twitter = `@${handle}`
const href = `https://www.twitter.com/${twitter}`
const props = {attrs: {href}, style:{color: "white", marginLeft: ".5em"}}
return h("span", {attrs:{"aria-hidden": true}}, [name, h("a", props, [twitter])])
}
}
并将模板更改为:
<div class="author">
<contributor :contributor="beer.contributor"></contributor>
<cite></cite>
</div>
这是您的 codepen updated来证明这一点。
关于javascript - 将 ES5 函数添加到使用 babel 编译的 vuejs 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51218942/