我有几个Codemirror实例,我想选择其中一个,我该怎么做?
我尝试过var basicEditor = VueCodemirror.CodeMirror($('#basic').get(0));
,但是没有用。
这是我的代码。
Vue.use(window.VueCodemirror);
Vue.component('edit', {
data: function () {
return {
basicHtml: '',
mediaHtml: '',
codeMirrorOptions: {
tabSize : 4,
lineNumbers: true,
line : true,
mode : 'text/x-scss',
gutters : ["CodeMirror-lint-markers"],
lint : true,
matchBrackets : true,
autoCloseBrackets: true
},
}
},
template: `<div>
<label>Basic Styles</label>
<codemirror
v-model="basicHtml"
:options="codeMirrorOptions"
@input="updateBasicHtml(basicHtml)"
id="basic"
></codemirror>
<label>Media Queries</label>
<codemirror
v-model="mediaHtml"
:options="codeMirrorOptions"
@input="updateMediaHtml(mediaHtml)"
id="media"
></codemirror>
<br/></div>`,
mounted: function () {
this.keyEvent();
},
created: function () {
this.createStyle();
},
methods: {
keyEvent() {
$(document).ready(function () {
$('#basic, #media').keyup(function (e) {
e.preventDefault();
var basicCss = {
'width': '865px',
'position': 'relative',
'top': '0',
'left': '0',
'right': '-2.58333px',
'bottom': '-14px',
'height': '300px',
'z-index': 'auto'
};
var fullscreenCss = {
'position': 'fixed',
'width': 'auto',
'top': '0',
'left': '0',
'right': '0',
'bottom': '0',
'height': 'auto',
'z-index': '9999'
};
console.log("Key pressed " + e.key);
var active = $(document.activeElement);
var editor = active.parent().parent();
if (e.which == 122) {
if (!editor.hasClass('activeFullScreen')) {
editor.addClass('activeFullScreen');
editor.css(fullscreenCss);
}
}
if (e.which == 27) {
if (editor.hasClass('activeFullScreen')) {
editor.removeClass('activeFullScreen');
editor.css(basicCss);
}
}
});
});
},
updateBasicHtml(basicHtml) {
console.log(basicHtml);
},
updateMediaHtml(mediaHtml) {
console.log(mediaHtml);
},
createStyle() {
$("#createStyleButton").on('click', () => {
console.log('createStyle')
var basicEditor = VueCodemirror.CodeMirror($('#basic').get(0));
console.log(basicEditor.doc.getAllMarks()); //My tried method.
return false;
});
}
}
})
window.vue = new Vue({
el : '#vue',
props: [],
data : () => {
return {
};
},
});
答案 0 :(得分:2)
尝试使用vue ref而不是id定义组件,如下所示:
<codemirror
v-model="mediaHtml"
:options="codeMirrorOptions"
@input="updateMediaHtml(mediaHtml)"
ref="basic"
></codemirror>
并在您的“ createStyle()”方法中,您应该可以执行以下操作:
this.$refs.basic.codemirror